采用Filter的方法解决Servlet的编码问题

这样比你自己在Servlet代码中硬编码request.setCharacterEncoding, response.setCharacterEncoding方便多了

总之,如果你添加了这个filter,配置好了web.xml,那么如果还出现乱码问题,你就去检查你的JSP和HTML代码中的encoding选项吧(charset, pageEncoding, meta.content之类的),看看是否和你在web.xml中配置的filter的encoding相匹配

CharacterEncodingFilter.java

 1 public class CharacterEncodingFilter implements Filter {
 2     protected String encoding = null; 
 3     protected FilterConfig filterConfig = null; 
 4     protected boolean enable = false; 
 5     public void destroy() { 
 6         this.encoding = null; 
 7         this.filterConfig = null; 
 8     } 
 9     public void doFilter(ServletRequest request, ServletResponse response, 
10                            FilterChain chain) throws IOException, ServletException { 
11         if (this.enable) {
12             String encoding = selectEncoding(request); 
13             if (encoding != null && !encoding.equals("")) { 
14                 System.out.println(this + ": ignore = true " + encoding);
15                 request.setCharacterEncoding(encoding); //Overrides the name of the character encoding used in the body of this request. This method must be called prior to reading request parameters or reading input using getReader().
16                 response.setCharacterEncoding(encoding);
17             }
18         }
19         // Pass control on to the next filter 
20         chain.doFilter(request, response); 
21      } 
22      public void init(FilterConfig filterConfig) throws ServletException { 
23          this.filterConfig = filterConfig; 
24          this.encoding = filterConfig.getInitParameter("encoding");
25          // 
26          String enable = filterConfig.getInitParameter("enable");
27          if (enable.equalsIgnoreCase("true")) {
28             this.enable = true;
29          } else {
30             this.enable = false;
31          }
32       } 
33       protected String selectEncoding(ServletRequest request) { 
34           return (this.encoding); 
35       } 
36 }

web.xml

<filter> 
         <filter-name>charset-encoding</filter-name> 
         <filter-class>cn.mldn.lxh.encoding.filter.CharacterEncodingFilter</filter-class> 
         <init-param> 
             <param-name>encoding</param-name> 
             <param-value>UTF-8</param-value> 
         </init-param> 
         <init-param> 
             <param-name>enable</param-name> 
             <param-value>true</param-value> 
         </init-param> 
</filter>

<filter-mapping> <filter-name>charset-encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值