1.新建过滤器类
(1)实现filter接口
(2)重写init、doFilter、destroy方法
1 @Override 2 public void init(FilterConfig filterconfig) throws ServletException { 3 this.filterconfig = filterconfig; 4 5 } 6 7 @Override 8 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { 9 String charset=this.filterconfig.getInitParameter("charset"); 10 request.setCharacterEncoding(charset); 11 response.setCharacterEncoding(charset); 12 response.setContentType("text/html;charset="+charset+""); 13 chain.doFilter(request, response); 14 } 15 16 @Override 17 public void destroy() { 18 // TODO Auto-generated method stub 19 20 }
2.配置web.xml文件
1 <filter> 2 <description>编码格式配置</description> 3 <filter-class>com.bjsxt.util.filter.CharacterFilter</filter-class> 4 <filter-name>CharacterFilter</filter-name> 5 <init-param> 6 <param-name>charset</param-name> 7 <param-value>utf-8</param-value> 8 </init-param> 9 </filter> 10 <filter-mapping> 11 <filter-name>CharacterFilter</filter-name> 12 <url-pattern>/*</url-pattern> 13 </filter-mapping>
3.注意
编码个式可以在web.xml中设置,也可以直接在doFilter中设置。