Filter过滤器处理中文乱码

注意问题:在学习用selvert的过滤器filter处理中文乱码时,在filter配置初始化时用了utf-8处理中文乱码,而在提交的jsp页面中却用了gbk。虽然两种都可以出来中文乱码,但是却造成了处理乱码的格式不一致。所以编译出错。

解决方法:所有地方都用utf-8或gbk

 

//过滤器类
CharactorFilter.jsp
package cn.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 CharactorFilter implements Filter { //继承Filter类
//字符编码
String encoding=null;

public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if(encoding!=null){
//设置request字符编码
request.setCharacterEncoding(encoding);
//设置response字符编码
response.setContentType(“text/html;charset=”+encoding);
}
//传递给下一个过滤器
chain.doFilter(request, response);

}

public void init(FilterConfig filterConfig) throws ServletException {
//获取初始化参数
encoding=filterConfig.getInitParameter(“encoding”);

}

public void destroy() {
// TODO Auto-generated method stub
encoding=null;
}

}

web.xml
<filter>      <!–注意这里是filter,不要配置成servlet–>
<filter-name>CharactorFilter</filter-name>    <!–过滤器名称–>
<filter-class>cn.com.Filter.CharactorFilter</filter-class>  <!–过滤器的完整类名–>
<init-param>   <!–初始化参数–>
<param-name>encoding</param-name>  <!–参数名称–>
<param-value>utf-8</param-value>   <!–参数值–>
</init-param>
</filter>
<filter-mapping> <!–过滤器映射–>
<filter-name>CharactorFilter</filter-name><!–过滤器名称–>
<url-pattern>/*</url-pattern><!–URL映射,给所有页面处理乱码–>
</filter-mapping>

标签