1. 程式人生 > >通過filter過濾器進行中文處理

通過filter過濾器進行中文處理

oid param 過濾器 局限 很多 public ppi 通過 value

一、使用servlet處理的局限性

可以通過:

request.setCharacterEncoding("UTF-8");

正確獲取UTF-8編碼的中文,但是如果有很多servlet都需要獲取中文,那麽就必須在每個Servlet中增加這段代碼。

有一個簡便的辦法,那就是通過Filter過濾器進行中文處理 ,那麽所有的Servlet都不需要單獨處理了。

二、使用Filter處理

創建一個EncodingFilter,設置如下代碼:

 1 package filter;
 2  
 3 import java.io.IOException;
 4 import java.text.SimpleDateFormat;
5 import java.util.Date; 6 7 import javax.servlet.Filter; 8 import javax.servlet.FilterChain; 9 import javax.servlet.FilterConfig; 10 import javax.servlet.ServletException; 11 import javax.servlet.ServletRequest; 12 import javax.servlet.ServletResponse; 13 import javax.servlet.http.HttpServletRequest;
14 import javax.servlet.http.HttpServletResponse; 15 16 public class EncodingFilter implements Filter { 17 18 @Override 19 public void destroy() { 20 21 } 22 23 @Override 24 public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) 25 throws
IOException, ServletException { 26 HttpServletRequest request = (HttpServletRequest) req; 27 HttpServletResponse response = (HttpServletResponse) res; 28 29 request.setCharacterEncoding("UTF-8"); 30 31 chain.doFilter(request, response); 32 } 33 34 @Override 35 public void init(FilterConfig arg0) throws ServletException { 36 37 } 38 39 }

doFilter方法的第一個參數req,是ServletRequest 類型的,不支持setCharacterEncoding,所以要先強制轉換為HttpServletRequest

三、配置web.xml

1 <filter>
2     <filter-name>EncodingFilter</filter-name>
3     <filter-class>filter.EncodingFilter</filter-class>
4 </filter>
5  
6 <filter-mapping>
7     <filter-name>EncodingFilter</filter-name>
8     <url-pattern>/*</url-pattern>
9 </filter-mapping>


在SpringMVC中,web.xml配置與上面類似:

 1 <filter> 
 2         <filter-name>CharacterEncodingFilter</filter-name> 
 3         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 
 4         <init-param> 
 5             <param-name>encoding</param-name> 
 6             <param-value>utf-8</param-value> 
 7         </init-param> 
 8     </filter> 
 9     <filter-mapping> 
10         <filter-name>CharacterEncodingFilter</filter-name> 
11         <url-pattern>/*</url-pattern> 
12     </filter-mapping> 

通過filter過濾器進行中文處理