java 使用过滤器实现中文处理

 1 package cn.jbit.house.filter;
 2 
 3 import java.io.IOException;
 4 import java.io.UnsupportedEncodingException;
 5 
 6 import javax.servlet.Filter;
 7 import javax.servlet.FilterChain;
 8 import javax.servlet.FilterConfig;
 9 import javax.servlet.ServletException;
10 import javax.servlet.ServletRequest;
11 import javax.servlet.ServletResponse;
12 import javax.servlet.http.HttpServletRequest;
13 import javax.servlet.http.HttpServletRequestWrapper;
14 import javax.servlet.http.HttpServletResponse;
15 
16 public class CharacterFilter implements Filter {
17 
18     private String encoding="utf-8";
19     
20     public void doFilter(ServletRequest request, ServletResponse response,
21             FilterChain chain) throws IOException, ServletException {
22         HttpServletRequest req = (HttpServletRequest)request;
23         HttpServletResponse resp = (HttpServletResponse)response;
24         
25         resp.setContentType("text/html;charset="+encoding);
26         
27         chain.doFilter(new RequestWrapper(req), resp);
28     }
29 
30     public void init(FilterConfig arg0) throws ServletException {
31     }
32     public void destroy() {
33     }
34     /**
35      * 请求的包装器,用于覆盖getParameter方法,在获取参数时全部进行转码
36      */
37     private class RequestWrapper extends HttpServletRequestWrapper {
38 
39         public RequestWrapper(HttpServletRequest request) {
40             super(request);
41         }
42         public String getParameter(String name) {
43             String value = super.getParameter(name);
44             if(null == value) return null;
45             value = encoding(value);
46             return value;
47         }
48         public String[] getParameterValues(String name) {
49             String[] temp = super.getParameterValues(name);
50             for(int i=0;i<temp.length;i++) {
51                 temp[i] = encoding(temp[i]);
52             }
53             return temp;
54         }
55         
56         private String encoding(String str) {
57             try {
58                 return new String(str.getBytes("iso-8859-1"),encoding);
59             } catch (UnsupportedEncodingException e) {
60                 e.printStackTrace();
61             }
62             return null;
63         }
64         
65     }
66 
67 }

实现思路 重写getParameter(String name) 、getParameterValues(String name) 方法 实现对post 和 get方式请求的 转码  没时间细写了 以后再修改

posted @ 2012-08-28 19:26  ×jokey  阅读(691)  评论(0编辑  收藏  举报