Article From:https://www.cnblogs.com/pingxin/p/p00096.html

Request and response objects representing user requests and responses can be obtained in the filter, so the Decorator pattern can be used in programming to wrap the request and response objects, and then pass the wrapped objects to the catalog.Target resources to achieve some special needs.

I. Decorator design pattern

1.1、DecoratorIntroduction of design patterns

  When an object’s method does not meet the needs of business, there are usually 2 ways to enhance the method.

  1. Writing subclasses to cover the need to enhance.
  2. Use Decorator design pattern to enhance the method.

  In Dr. Yan Hong’s book “JAVA and model”, the first thing to describe is the Decorator mode:The decoration mode is also called the Wrapper mode. Decorative patterns, which extend the functionality of objects in a transparent manner to the client, are an alternative to inheritance relationships.Decorative pattern is to dynamically extend the function of an object without changing the original class file and using inheritance. It is through the creation of a packaging object, that is, decoration to wrap the real object.

  So when we need to enhance objects in practical applications, which method is better? There is no specific formula, it can only be used in specific ways according to specific needs.In one case, you have to use the Decorator design pattern: Enhanced objects that developers can only get their objects, not their class files。For example, request, response objects, which developers can manipulate through Sun’s HttpServletRequest response interface in servlets, are compiled by Tomcat server vendorsThe implementation class of request and response interface is written. When a web server calls a servlet, it creates objects with the implementation classes of these interfaces and passes them to the servlet program. In this case, developers do not know the R written by the server manufacturer at all.What is the implementation class of equest and response interface? You can only get the objects provided by the server vendor in the program, so you can only use the Decorator design pattern to enhance these objects.

1.2、DecoratorImplementation of design patterns

  1.First look at what interfaces or parent classes the enhanced object inherits, and write a class to inherit those interfaces or parent classes as well.
  2.A variable is defined in the class, and the type of variable is to enhance the type of the object.
  3.Define a constructor in the class to receive objects that need to be enhanced.
  4.Coverage needs to be enhanced, and enhanced code is written.

 Two, use Decorator design pattern to enhance request objects.

  Servlet API The default implementation class HttpServletRequestWrapper for the Decorator design pattern of a request object is provided, and the HttpServletRequestWrapper class implements the request connectionAll the methods in the port, but the internal implementation of these methods only calls the corresponding method of the wrapped request object to avoid the need for users to implement all the methods in the request interface when enhancing the request object.

2.1、Using Decorator mode to package request objects to solve Chinese garbled problem under get and post request mode

  Write a filter CharacterEncodingFilter for handling Chinese garbled code. The code is as follows:

Copy code ></span></div><pre>  1 package me.gacl.web.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 import javax.servlet.http.HttpServletRequestWrapper;
 13 import javax.servlet.http.HttpServletResponse;
 14 
 15 /**
 16 * @ClassName: CharacterEncodingFilter
 17 * @Description: This filter is used to solve the Chinese garbled problem in the way of get and post request.18 * @author: lonely Wolf19 * @date: 2014-8-31 11:09:37 p.m.20 *21 * /22 public class CharacterEncodingFilter implements Filter {Twenty-three24 private FilterConfig filterConfig = null;25 / / set default character encoding26 private String defaultCharset =
Copy code ></span></div></div><p>  Configure CharacterEncodingFilter in web.xml file</p><div class=
Copy code ></span></div><pre> 1 <!--Configure character filter to solve the Chinese garbled problem under get and post request mode -->2 < filter>3 < filter-name> CharacterEncodiNgFilter< /filter-name>4 < filter-class> me.gacl.web.filter.CharacterEncodingFilter< /filter-class>5 < /filter>Six7 < filter-mapping>8 < filter-namE> CharacterEncodingFilter< /filter-name>9 < url-pattern> /*< /url-pattern>10 < /filter-mapping></pre><div class=Copy code ></span></div></div><p>  Write the JSP test page as follows:</p><div class=
Copy code ></span></div><pre> 1 <%@ page language=
Copy code ></span></div></div><p>  Write ServletDemo1 that handles user requests</p><div class=
Copy code ></span></div><pre> 1 package me.gacl.web.controller;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.http.HttpServlet;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 
11 public class ServletDemo1 extends HttpServlet {
12 
13     public void doGet(HttpServletRequest request, HttpServletResponse response)
14             throws ServletException, IOException {
15         //Receiving parameters16 String username = request.getParameter (
Copy code ></span></div></div><p>  The test results are as follows:</p><p>  <img src=

  From the running results, we can see that the Chinese scrambling problem can be solved perfectly, whether it is get request or post request.

2.2、Using Decorator mode to wrap request objects to implement HTML tag escape function

  Write a HTML escape filter. The code is as follows:

Copy code ></span></div><pre>  1 package me.gacl.web.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 import javax.servlet.http.HttpServletRequestWrapper;
 13 import javax.servlet.http.HttpServletResponse;
 14 
 15 /**
 16 * @ClassName: HtmlFilter
 17 * @Description: htmlEscape filter18 * @author: lonely Wolf19 * @date: 2014-9-2 11:28:41 p.m.20 *21 * /22 public class HtmlFilterImplements Filter {Twenty-three24 public void doFilter (ServletRequest req, ServletResponse resp,Twenty-fiveFilterChain chain) throws IOException, ServletException {Twenty-six27 HttpServletRequest request = (HttpServletRequest) req;28 HttpServletResponse response = (HttpS)ErvletResponse) resp;Twenty-nine30 MyHtmlRequest myrequest = new MyHtmlRequest (request);Thirty-oneChain.doFilter (myrequest, response);Thirty-two33}Thirty-fourThirty-five36 public void DEstroy () {Thirty-seven38}Thirty-nineForty41 public void init (FilterConfig filterConfig)Throws ServletException {Forty-two43}44}Forty-five46 / * * * *47 * @ClassName: MyHtmlRequest48 * @Description: wrapper request objects in Decorator mode to implement HTML tag escape function.49 * @author: lonely Wolf50 * @date: 2014-9-211:29:09 PM51 *52 * /53 class MyHtmlRequest extends HttpServletRequestWrapper {Fifty-four55 prIvate HttpServletRequest request;Fifty-six57 public MyHtmlRequest (HttpServletRequest request) {Five8 super (request);59 this.request = request;60}Sixty-one62 / * coverage needs enhanced getPaRameter method63 * @see javax.servlet.ServletRequestWrapper#getParameter (java.lang.String)Sixty-four* * /65 @Override66 public String getParameter (String name) {67 String value =This.request.getParameter (name);68 If (value = = null) {69 return null;Seventy}71 / / call the HTML label in filter escape value72 return filter (value);73}Seventy-fourSeventy-five/ * * * * *76 * @Method: filter77 * @Description: filtering HTML tags in content78 * @Anthor: lonely WolfSeventy-nine* @param message80 * @return81 * /82 public String filter (String message) {Eighty-threeIf (message = = null) {84 return null;85}86 char content[]= new char[message.length ()];87 message.getChars (0, message.length (), content, 0);Eighty-eightStringBuffer result = new StringBuffer (content.length + 50);89 for (int i = 0; I <Content.length; i++) {90 switch (content[i]) {91 case'< ':Ninety-twoResult.append (
Copy code ></span></div></div><p>  Configure HtmlFilter in web.xml file</p><div class=
Copy code ></span></div><pre> 1 <!--Configure the Html filter, the HTML tag --> in the escape.2 < filter>3 < filter-name> HtmlFilter< /filter-nAme>4 < filter-class> me.gacl.web.filter.HtmlFilter< /filter-class>5 < /fiLter>Six7 < filter-mapping>8 < filter-name> HtmlFilter< /filter-name>9 < url-pattern> /*< /url-pattern>10 < /filter-mapping></pre><div class=Copy code ></span></div></div><p>  Write the JSP test page as follows:</p><div class=
Copy code ></span></div><pre> 1 <%@ page language=
Copy code ></span></div></div><p>  Write ServletDemo2 that handles user requests</p><div class=
Copy code ></span></div><pre> 1 package me.gacl.web.controller;
 2 
 3 import java.io.IOException;
 4 
 5 import javax.servlet.ServletException;
 6 import javax.servlet.http.HttpServlet;
 7 import javax.servlet.http.HttpServletRequest;
 8 import javax.servlet.http.HttpServletResponse;
 9 
10 public class ServletDemo2 extends HttpServlet {
11 
12     public void doGet(HttpServletRequest request, HttpServletResponse response)
13             throws ServletException, IOException {
14         //Getting user input15 String message = request.getParameter (
Copy code ></span></div></div><p>The test results are as follows:</p><p>  <img src=

  As you can see from the running results, all the HTML tags are exported.

2.3、Wrapping request objects in Decorator mode to implement sensitive character filtering

  Write a sensitive character filter. The code is as follows:

Copy code ></span></div><pre>  1 package me.gacl.web.filter;
  2 
  3 import java.io.BufferedReader;
  4 import java.io.IOException;
  5 import java.io.InputStream;
  6 import java.io.InputStreamReader;
  7 import java.io.UnsupportedEncodingException;
  8 import java.util.ArrayList;
  9 import java.util.List;
 10 import javax.servlet.Filter;
 11 import javax.servlet.FilterChain;
 12 import javax.servlet.FilterConfig;
 13 import javax.servlet.ServletException;
 14 import javax.servlet.ServletRequest;
 15 import javax.servlet.ServletResponse;
 16 import javax.servlet.http.HttpServletRequest;
 17 import javax.servlet.http.HttpServletRequestWrapper;
 18 import javax.servlet.http.HttpServletResponse;
 19 
 20 /**
 21 * @ClassName: DirtyFilter
 22 * @Description: Sensitive word filter23 * @author: lonely Wolf24 * @date: 2014-9-6 10:43:11 a.m.25 *26 * /27 public class DirtyFiltEr implements Filter {Twenty-eight29 private FilterConfig config = null;Thirty31 @Override32 public void init (FilterConfig filterConfig) throws ServletException {33 this.config= filterConfig;34}Thirty-five36 @Override37 public void doFilter (ServletRequest req, S)ErvletResponse resp,38 FilterChain chain) throws IOException, ServletException {Thirty-nine40 HttpServletRequest request = (HttpServletRequest) req;41 HttpServletReSponse response = (HttpServletResponse) resp;42 DirtyRequest dirtyrequest = new DirtyRequeSt (request);Forty-three44 chain.doFilter (dirtyrequest, response);45}Forty-sixForty-seven@Override48 public void destroy () {Forty-nine50}Fifty-one52 / * * * *53 * @Method: GeTDirtyWords54 * @Description: to get sensitive characters.55 * @Anthor: lonely Wolf56 *57 * @returnFifty-eight* * /59 private List< String> getDirtyWords () {60 List< String> dirtyWords= new ArrayList< String> ();61 String dirtyWordPath = config.getInitParameter (
Copy code ></span></div></div><p>  Configure DirtyFilter in web.xml file</p><div class=
Copy code ></span></div><pre> 1  <!--Configure sensitive character filter -->2 < filter>3 < filter-name> DirtyFilter< /filter-name>Four< filter-class> me.gacl.web.filter.DirtyFilter< /filter-class>5 <!! - configure filter.Sensitive character file -->6 < init-param>7 < param-name> dirtyWord< /param-name>8 < param-value> /WEB-INF/DirtyWord.txt< /param-value>9 < /init-paraM>10 < /filter>Eleven12 < filter-mapping>13 < filter-name> DirtyFilter< /filter-name>14 < url-pattern> /*< /url-pattern>15 < /filter-mapping></pre><div class=Copy code ></span></div></div><p>  When the user fills in something that contains sensitive characters, these sensitive characters are replaced in the DirtyFilter filter.</p><p>  If we combine these three filters, CharacterEncoding Filter, HtmlFilter, DirtyFilter, we’ll wrap the request object three times, the request objectThe getParameter method has been rewritten three times, which greatly enhances the function of the getParameter method. It can solve the problems of Chinese scrambling, HTML tag escaping and sensitive character filtering at the same time.</p><p>  In practice, the three filters mentioned above can be merged into one, so that the merged filter can solve Chinese scrambling, HTML tag escaping, and sensitive character filtering, such as:</p><div class=
Copy code ></span></div><pre>  1 package me.gacl.web.filter;
  2 
  3 import java.io.BufferedReader;
  4 import java.io.IOException;
  5 import java.io.InputStream;
  6 import java.io.InputStreamReader;
  7 import java.io.UnsupportedEncodingException;
  8 import java.util.ArrayList;
  9 import java.util.List;
 10 
 11 import javax.servlet.Filter;
 12 import javax.servlet.FilterChain;
 13 import javax.servlet.FilterConfig;
 14 import javax.servlet.ServletException;
 15 import javax.servlet.ServletRequest;
 16 import javax.servlet.ServletResponse;
 17 import javax.servlet.http.HttpServletRequest;
 18 import javax.servlet.http.HttpServletRequestWrapper;
 19 import javax.servlet.http.HttpServletResponse;
 20 
 21 /**
 22 * @ClassName: AdvancedFilter
 23 * @Description: This filter is used to solve Chinese scrambling, escape the HTML tags in the content, and filter sensitive characters in the content.24 * @author: lonely Wolf25 * @date: 2014-9-6 6:17:37 p.m.26 *Two7 * /28 public class AdvancedFilter implements Filter {Twenty-nine30 private FilterConfig filterCoNfig = null;31 / / set default character encoding32 private String defaultCharset =
Copy code ></span></div></div><p>  Configure AdvancedFilter in web.xml file</p><div class=
Copy code ></span></div><pre> 1   <filter>
 2       <filter-name>AdvancedFilter</filter-name>
 3       <filter-class>me.gacl.web.filter.AdvancedFilter</filter-class>
 4       <init-param>
 5          <param-name>charset</param-name>    
 6          <param-value>UTF-8</param-value>
 7     </init-param>
 8       <init-param>
 9          <param-name>dirtyWord</param-name>    
10          <param-value>/WEB-INF/DirtyWord.txt</param-value>
11     </init-param>
12   </filter>
13   
14   <filter-mapping>
15       <filter-name>AdvancedFilter</filter-name>
16       <url-pattern>/*</url-pattern>
17   </filter-mapping></pre><div class=Copy code ></span></div></div><p>  AdvancedFilterThe filter also has the functions of resolving Chinese scrambling, escaping HTML tags in the content, and filtering sensitive characters in the content.</p><h2><span id=Three, use Decorator design pattern to enhance response objects.

  Servlet  API The default implementation class HttpServletResponseWrapper, which provides the Decorator design pattern for the response object, and the HttpServletResponseWrapper class, which implements the responseAll the methods in the interface, but the internal implementation of these methods only calls the corresponding method of the wrapped response object to avoid the need for users to implement all the methods in the response interface when they enhance the response object.

3.1、responseEnhance case — compress response text content

  The HttpServletResponseWrapper object is applied to compress the response text content.

  Specific idea: pass filter to the target page to pass a custom response object. In the custom response object, override the getOutputStream method and getWriter method so that the target resource calls this method to output the pageContent is obtained by our custom ServletOutputStream object. In our custom ServletOuputStream object, we override the write method to write the data out into a buffer. When page completion is lostAfter that, we can get the data written by the page in the filter, so we can call GzipOuputStream to compress the data and then write it to the browser to complete the compression function of the response positive file.

  Compiling the compression filter is as follows:

Copy code ></span></div><pre>  1 package me.gacl.web.filter;
  2 
  3 import java.io.ByteArrayOutputStream;
  4 import java.io.IOException;
  5 import java.io.OutputStreamWriter;
  6 import java.io.PrintWriter;
  7 import java.util.zip.GZIPOutputStream;
  8 
  9 import javax.servlet.Filter;
 10 import javax.servlet.FilterChain;
 11 import javax.servlet.FilterConfig;
 12 import javax.servlet.ServletException;
 13 import javax.servlet.ServletOutputStream;
 14 import javax.servlet.ServletRequest;
 15 import javax.servlet.ServletResponse;
 16 import javax.servlet.http.HttpServletRequest;
 17 import javax.servlet.http.HttpServletResponse;
 18 import javax.servlet.http.HttpServletResponseWrapper;
 19 
 20 /**
 21 * @ClassName: GzipFilter
 22 * @Description: The compression filter compresses the text in the web application and then outputs it to the browser.23 * @author: lonely Wolf24 * @date: 2014-9-7 10:52:42 a.m.25 *26 * /Twenty-sevenPublic class GzipFilter implements Filter {Twenty-eight29 public void doFilter (ServletRequest req, S)ErvletResponse resp,30 FilterChain chain) throws IOException, ServletException {Thirty-one32 HttpServletRequest request = (HttpServletRequest) req;33 HttpServletReSponse response = (HttpServletResponse) resp;Thirty-four35 BufferResponse myresponse = nEW BufferResponse (response);36 chain.doFilter (request, myresponse);37 / / take out data in cacheAfter compressing, call the browser again.38 byte out[] = myresponse.getBuffer ();39 System.out.println (
Copy code ></span></div></div><p>  Configuring the compression filter in web.xml</p><div class=
Copy code ></span></div><pre> 1  <filter>
 2       <description>Configure compression filter < /description>3 < filter-name> GzipFilter< /filter-name>4 <Filter-class> me.gacl.web.filter.GzipFilter< /filter-class>5 < /filter>Six7 &The output of LT!! --jsp file is compressed by compression filter before output -->8 < filter-mapping>9 < filter-name> GzipFIlter< /filter-name>10 < url-pattern> *.jsp< /url-pattern>11 <!! - configured.The interception mode of the filter is -->12 <!! - for passing in Servlet13 request.getRequestDispatcher (
Copy code ></span></div></div><h3><span id= 3.2、responseAugmented case — cache data to memory

  For the data rarely updated in the page, such as commodity classification, in order to avoid querying the classification data from the database every time, the classification data can be cached in memory or files to reduce the database pressure and improve the system response speed.

  Write a filter for cached data. The code is as follows:

Leave a Reply

Your email address will not be published. Required fields are marked *