本文转自http://blog.csdn.net/l271640625/article/details/6388690

 

        大家都知道,在jsp里乱码是最让人讨厌的东西,有些乱码出来的莫名其妙,给开发带来很大困扰,但搞一个乱码过滤器就一切都解决了,配置好之后,你并不需要在页面里进行转码之类的。

        首先,写一个过滤器类,如下:

 1 package filter;  
 2   
 3 import java.io.IOException;  
 4   
 5 import javax.servlet.Filter;  
 6 import javax.servlet.FilterChain;  
 7 import javax.servlet.FilterConfig;  
 8 import javax.servlet.ServletException;  
 9 import javax.servlet.ServletRequest;  
10 import javax.servlet.ServletResponse;  
11 import javax.servlet.http.HttpServletRequest;  
12   
13 public class PageEncodingFilter implements Filter{  
14   
15     private String encoding = "UTF-8";  
16     protected FilterConfig filterConfig;  
17       
18       
19     public void init(FilterConfig filterConfig) throws ServletException {  
20         this.filterConfig = filterConfig;  
21         //本过滤器默认编码是UTF-8,但也可以在web.xml配置文件里设置自己需要的编码  
22         if(filterConfig.getInitParameter("encoding") != null)  
23             encoding = filterConfig.getInitParameter("encoding");  
24     }  
25   
26     public void doFilter(ServletRequest srequset, ServletResponse sresponse,  
27             FilterChain filterChain) throws IOException, ServletException {  
28         HttpServletRequest request = (HttpServletRequest)srequset;  
29         request.setCharacterEncoding(encoding);  
30         filterChain.doFilter(srequset, sresponse);  
31     }  
32       
33     public void destroy() {  
34         this.encoding = null;  
35     }  
36   
37 }  

        然后,在web.xml里配置,如下:

 1 <filter>  
 2         <filter-name>Encoding</filter-name>  
 3         <filter-class>filter.PageEncodingFilter</filter-class>  
 4         <init-param>  
 5             <param-name>encoding</param-name>  
 6             <param-value>UTF-8</param-value>  
 7         </init-param>  
 8     </filter>  
 9       
10     <filter-mapping>  
11         <filter-name>Encoding</filter-name>  
12         <url-pattern>/*</url-pattern>  
13     </filter-mapping>

        到这里,一切就OK了,你可以放心的写代码了,而不会担心出现乱码了。

posted on 2013-11-04 21:26  书中叶  阅读(324)  评论(0编辑  收藏  举报