Servlet过滤器的相关知识点和过滤过程,已经总结在我的笔记上了,这里我就不多说了。下面是自己利用servlet过滤器处理乱码问题,解决了这么多天来因为乱码而需要每次都进行处理的头疼问题。
代码如下:
public class CodeQuestion implements Filter {
private String charset="UTF-8";
private FilterConfig congfig;
@Override
public void destroy() {
congfig=null;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding(charset);
response.setContentType("text/html;charset='"+charset+"'");
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
this.congfig=arg0;
}
}
DD文件如下:
<filter>
<filter-name>EncodingFilter</filter-name>
<filter-class>cn.itcast.filter_codeQuestion.CodeQuestion</filter-class>
</filter>
<filter-mapping>
<filter-name>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>