JSP中文乱码过滤器问题----急,在线等。
在网上看了好久,还是没解决了。高手们帮帮忙吧。
我贴代码。
web.xml配置如下。
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name></display-name> <!--中文乱码处理过滤--> <filter> <filter-name>EncodingFilter</filter-name> <filter-class>com.filter.Filter_charset</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>EncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--中文乱码处理过滤--> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list></web-app>
package com.filter;import java.io.IOException;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;public class Filter_charset implements Filter{ protected String encoding = null; // 接收字符编码 public void destroy() { // TODO Auto-generated method stub this.encoding = null; } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub if (this.encoding != null) { request.setCharacterEncoding(this.encoding); response.setCharacterEncoding(this.encoding); System.out.println(this.encoding); } chain.doFilter(request, response); } public void init(FilterConfig filterConfig) throws ServletException { // TODO Auto-generated method stub this.encoding = filterConfig.getInitParameter("encoding"); }}
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <head> </head> <body> <form action="TEST/filter/1.jsp"> 输入<input type="text" name="name"><br> <input type="submit" value="提交"> </form> </body></html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><html> <head> </head> <body> <% String name = request.getParameter("name");//得到提交表单的输入内容 //name = new String(name.getBytes("iso-8859-1"), "utf-8");//我用这个是能够解决乱码问题的,但是我想学习用过滤器 out.print(name);//输出 %> </body></html>
URL默认编码集市ISO-8859-1,可以修改。
[解决办法]
我看了你的代码,大致相同。提交表单,我一般用的是post,如果用get提交汉字,需要加密以后在提交,在后台再解密,这样才不是乱码。支持1楼