Request response distortion problem solving (using Filter)

EzrealYi


 

Previous:

     Before writing this note for note design patterns are introduced:
     Benpian note will be used to design pattern: decorative (packaging) design pattern
          (1) Decoration (package) design pattern formulas:
               ① define a class that implements the interface to the object to be decorated
               ② Define a member variable, remember the decorative object reference
               ③ define a constructor method, passing the decorated object instance
               ④ rewriting method to modify
               ⑤ method does not require rewriting, call the original methods are decorative objects
 
          (2) When using a decorative design pattern
               When we need to be enhanced to a class, class after class of enhancement is no longer current category
                    For example: There is now a Cat and Dog Animal class are all types of animals, it can be the direct successor
                                                                      Now a new "electronic dog", outside the scope of the animal, but there are ways in which the need, at this time we chose to use decorative (package) design pattern
 
A: Demand: unified solution request parameters Chinese garbled
 
Second, the optimization ideas:
 Using a filter before the servlet request arrives, the request object is encoded first set
 Requires that all requests should be carried out to set the encoding, so all of the request should interception, enhanced, then the web.xml should be added:
1  <! - set the encoding -> 
2      < context-param > 
. 3          < param-name > charset </ param-name > 
. 4          < param-value > UTF-. 8 </ param-value > 
. 5      </ context-param > 
. 6  
. 7      <! - configuration distortion filter -> 
. 8      < filter > 
. 9          < filter-name > EncodingFilter </ filter-name > 
10          <! - package name and file name ->
11         <filter-class>com.zy.web.Filter.EncodingFilter</filter-class>
12         <init-param>
13             <param-name>charset</param-name>
14             <param-value>UTF-8</param-value>
15         </init-param>
16     </filter>
17     <filter-mapping>
18         <filter-name>EncodingFilter</filter-name>
19         <url-pattern>/*</url-pattern>
20     </filter-mapping>

 

Three: code implementation:

     1, a filter codes
 1 package com.zy.web.Filter;
 2 
 3 import com.zy.web.Encoding.EncodingRequest;
 4 
 5 import javax.servlet.*;
 6 import javax.servlet.http.HttpServletRequest;
 7 import javax.servlet.http.HttpServletResponse;
 8 import java.io.IOException;
 9 
10 public class EncodingFilter implements Filter {
11     @Override
12     public void init(FilterConfig filterConfig) throws ServletException {
13     }
14 
15     @Override
16     public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
17         // 将请求和响应强制转换成Http形式
18         HttpServletRequest request = (HttpServletRequest) req;
19         HttpServletResponse response = (HttpServletResponse) res;
20 
21         String charset = request.getParameter("charset");
22         if (charset == null || charset.isEmpty()) {
23             charset = "UTF-8";
24         }
25 
26         // 处理响应乱码
27         response.setContentType("text/html;charset=" + charset);
28         response.setCharacterEncoding(charset);
29         EncodingRequest encodingRequest = new EncodingRequest(request, charset);
30         chain.doFilter(req, res);
31     }
32 
33     @Override
34     public void destroy() {
35 
36     }
37 }

 

2, to enhance the custom class (EncodingRequest)

  . 1  Package com.zy.web.Encoding;
   2  
  . 3  Import the javax.servlet.http.HttpServletRequest;
   . 4  Import javax.servlet.http.HttpServletRequestWrapper;
   . 5  Import java.io.UnsupportedEncodingException;
   . 6  Import a java.util.Map;
   . 7  Import Java .util.Set;
   . 8  
  . 9  public  class EncodingRequest the extends the HttpServletRequestWrapper {
 10      Private String charset;
 . 11      // defines a member variable, used to hold the object constructor passed requset 
12 is      Private= Request the HttpServletRequest null ;
 13 is      // define a tag used to mark: requset in the current request for a parameter, whether the encoded 
14      Private  Boolean In Flag = to false ;
 15  
16      / ** 
. 17       * Constructs A GIVEN Request The Request Object Wrapping .
 18 is       *
 . 19       * @param Request The { @link the HttpServletRequest} wrapped to BE.
 20 is       * @param charset
 21 is       * @throws an IllegalArgumentException The Request IF null IS
 22 is       * / 
23 is      public EncodingRequest(HttpServletRequest request, String charset) {
 24         super(request);
 25         this.charset = charset;
 26         this.request = request;
 27     }
 28 
 29     @Override
 30     public Map<String, String[]> getParameterMap() {
 31         // 获得请求方式request.getMethod()方法
 32         String method = this.request.getMethod();
 33         // post请求
 34         if ("post".equalsIgnoreCase(method)) {
 35             //Encoding format set 
36              the try {
 37 [                  Request.setCharacterEncoding (charset);
 38 is              } the catch (UnsupportedEncodingException E) {
 39                  e.printStackTrace ();
 40              }
 41 is              the Map <String, String []> = Map the this .request.getParameterMap ();
 42 is              return map;
 43 is  
44 is          } the else  IF ( "get" .equalsIgnoreCase (Method)) {
 45              // get request
 46              @ analysis: each element of the get request requires the map for each parameter conversion, it is necessary traverse
 47             // first obtained set of map 
48              the Map <String, String []> = map the this .request.getParameterMap ();
 49  
50              // first parameter acquisition request, flag == false, the latter performs operation processing distortion amount
 51              / / second when the acquisition request parameters, flag == true, the subsequent processing is not executed, direct return of already encoded map set 
52 is              IF (in Flag) {
 53 is                  return map;
 54 is              }
 55              IF (map == null ) {
 56 is                  return  Super .getParameterMap ();
 57 is              } the else {
 58                  // then obtained map set Key 
59                 SET <String> key = map.keySet ();
 60                  // by key elements in the map taken out 
61 is                  for (String String: key) {
 62 is                      String [] = value as map.get (String);
 63 is                      // contact String need down in each of all traverse, conversion parameter 
64                      for ( int I = 0; I <value.length; I ++ ) {
 65                          the try {
 66                              String string2 = new new String (
 67                                      value [I] .getBytes ( " 8859-1-ISO " ), charset);
 68                              value [I] =string2;
 69                          } the catch (UnsupportedEncodingException E) {
 70                              e.printStackTrace ();
 71 is                          }
 72                      }
 73 is                  }
 74                  In Flag = to true ;
 75                  return Map;
 76              }
 77          } the else {
 78              // location request mode, the object processing can not customize using the processing method of the parent class 
79              return  Super .getParameterMap ();
 80          }
 81     }
 82 
 83     @Override
 84     public String[] getParameterValues(String name) {
 85         if(name == null || name.equals("")){
 86             return super.getParameterValues(name);
 87         }else{
 88             return this.getParameterMap().get(name);
 89         }
 90     }
 91 
 92     @Override
 93     public String getParameter(String name) {
 94         if(name == null || name.equals("")){
 95             return super.getParameter(name);
 96         }else{
 97             return this.getParameterValues(name)[0];
 98         }
 99     }
100 }

 

Guess you like

Origin www.cnblogs.com/ezrealyi/p/12466678.html