Filter编码过滤

      为了在后台统一设定编码,不必在每个servlet中单独设定编码,从而避免重复的劳作,又增加代码的可读性和可维护性的目的,使用Filter是一个很不错的选择。

1. EncodingFilter类

 1 public class EncodingFilter implements Filter{
 2     
 3     //设定默认编码
 4     private String charset = "UTF-8";
 5     private FilterConfig config;
 6     
 7     @Override
 8     public void destroy() {
 9         charset = null;
10         config = null;
11     }
12 
13     @Override
14     public void doFilter(ServletRequest request, ServletResponse response,
15             FilterChain chain) throws IOException, ServletException {
16         //设置请求响应字符编码
17         HttpServletRequest req = (HttpServletRequest)request;
18         HttpServletResponse res = (HttpServletResponse)response;
19         req.setCharacterEncoding(charset);
20         res.setContentType("text/html;charset=utf-8");
21         //对get请求编码统一处理
22         if(req.getMethod().equalsIgnoreCase("GET")){
23             //通过调用自己写的EncodingWrapper类,对request进行包装
24             EncodingWrapper wrapper = new EncodingWrapper(req,charset);
25             chain.doFilter(wrapper, res);
26         }else{
27             chain.doFilter(req, res);
28         }
29     }
30 
31     @Override
32     public void init(FilterConfig config) throws ServletException {
33         this.config = config;
34         //从web.xml配置中读取设定的编码方式
35         String charset = config.getServletContext().getInitParameter("charset");
36         if(StringUtils.isNotEmpty(charset)){
37             this.charset = charset;
38         }
39     }
40     
41 }
View Code

2. EncodingWrapper类

 1 public class EncodingWrapper extends HttpServletRequestWrapper{
 2     
 3     private String charset = "UTF-8";
 4     
 5     /**
 6      * 创建一个新的实例 EncodingWrapper.
 7      * @param request
 8      */
 9     public EncodingWrapper(HttpServletRequest request) {
10         super(request);
11     }
12     
13     /**
14      * 获取被装饰对象的引用和采用的字符编码
15      * @param request
16      * @param charset
17      */
18     public EncodingWrapper(HttpServletRequest request, String charset){
19         super(request);
20         this.charset = charset;
21     }
22     
23     @Override
24     public String getParameter(String name){
25         String value = super.getParameter(name);
26         if(StringUtils.isEmpty(value))return null;
27         try {
28             value = new String(value.getBytes("ISO-8859-1"),charset);
29             return value;
30         } catch (UnsupportedEncodingException e) {
31             e.printStackTrace();
32         }
33         return value;
34     }
35 
36 }
View Code

3. jsp页面

 1 <%@page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 <!DOCTYPE HTML>
 3 <html>
 4 <head>
 5     <title>servlet测试</title>
 6     <meta http-equiv="pragma" content="no-cache">
 7     <meta http-equiv="cache-control" content="no-cache">
 8     <meta http-equiv="expires" content="0">    
 9     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
10     <meta http-equiv="description" content="This is my page">
11     <style type="text/css">
12       *{margin:0;padding:0}
13       body{font-size:12px;font-family:"微软雅黑";color:#333;}
14       .wrap{width:640px;border:1px solid #333;}
15       input[type="text"]{width:300px;height:30px;margin:10px;outline:none;padding-left:10px;}
16       .wrap label{width:60px;display:inline-block;text-align:right}
17     </style>
18 </head>
19 <body>
20 <div class="wrap">
21    <form action="../ServletTest" method="get" >
22        <label> 用户名:</label><input type="text" name="username" /><br />
23        <label> 密码:</label><input type="text" name="password" />
24        <input type="submit" />
25    </form>
26 </div>
27 </body>
28 </html>
View Code

4. servletTest类

 1 //这种注解的方式不需要再web.xml中配置
 2 //@WebServlet(name = "MyFirstServlet", urlPatterns = {"/ServletTeaa"})
 3 public class ServletTest extends HttpServlet{
 4 
 5     private static final long serialVersionUID = 1L;
 6 
 7     @Override
 8     protected void doGet(HttpServletRequest req, HttpServletResponse resp)
 9             throws ServletException, IOException {
10         doPost(req,resp);
11     }
12 
13     @Override
14     protected void doPost(HttpServletRequest req, HttpServletResponse resp)
15             throws ServletException, IOException {
16         //有了统一的编码过滤器,以下两行代码可以“隐身”了
17         //req.setCharacterEncoding("utf-8");
18         //resp.setCharacterEncoding("utf-8");
19         System.out.println("进入了ServletTest");
20         String username = req.getParameter("username");
21         String password = req.getParameter("password");
22         System.out.println("用户名:"+username+",密码: "+password);
23         //resp.setContentType("text/html;charset=utf-8");
24         PrintWriter    out = resp.getWriter();
25         out.println("<html>");
26         out.println("<head>");
27         out.println("<title>Servlet编码测试</title>");
28         out.println("</head>");
29         out.println("<body>");
30         out.println("<h2>Servlet编码测试" + req.getContextPath() + "</h2>");
31         out.println("</body>");
32         out.println("</html>");
33         System.out.println("退出了ServletTest");
34     }
35 
36     @Override
37     public void service(ServletRequest req, ServletResponse res)
38             throws ServletException, IOException {
39         super.service(req, res);
40     }
41 
42 }

 

最后,在web.xml中作好配置

  <context-param>
      <param-name>charset</param-name>
      <param-value>UTF-8</param-value>
  </context-param>

  <!-- 过滤器配置 -->
  <filter>
      <description>统一编码过滤器</description>
      <filter-name>encodingFilter</filter-name>
      <filter-class>com.ue.filter.EncodingFilter</filter-class>
  </filter>
  <filter-mapping>
      <filter-name>encodingFilter</filter-name>
      <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <!-- servlet配置 -->
  <servlet>
      <description>servlet测试</description>
      <servlet-name>MyFirstServlet</servlet-name>
      <servlet-class>com.ue.servlet.ServletTest</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>MyFirstServlet</servlet-name>
      <url-pattern>/ServletTest</url-pattern>
  </servlet-mapping>

当然,你也可以直接在server.xml直接设置你的编码方式。

posted on 2016-03-17 14:48  hobbycc  阅读(354)  评论(0编辑  收藏  举报

导航