[JavaWeb] a practical case of Java filter and packaging design pattern

The request and response objects representing the user's request and response can be obtained in the filter. Therefore, in programming, the decorator mode can be used to wrap the request and response objects, and then pass the wrapping objects to the target resources, so as to realize some special requirements.

When the method of an object does not meet the business requirements, there are usually two ways to enhance the method: write a subclass to cover the method to be enhanced. The decorator design pattern is used to enhance the method. The beginning of Dr. Yan Hong's Book Java and patterns describes the decorator pattern as follows: the decorator pattern is also known as the wrapper pattern. Decoration mode extends the function of objects in a transparent way to the client, which is an alternative to inheritance. Decoration mode is to dynamically extend the function of an object without changing the original class file and using inheritance. It wraps the real object by creating a wrapper object, that is, decoration. So when we encounter the method of enhancing objects in practical application, which method is better? There is no specific formula for this, and only specific methods can be adopted according to specific requirements. However, in one case, the decorator design pattern must be used: that is, for the enhanced object, the developer can only get its object, not its class file. For example, request and response objects. The reason why developers can operate these objects in the servlet through the HttpServletRequest \ response interface defined by Sun company is that the Tomcat server manufacturer has written the implementation classes of request and response interfaces. When the web server calls the servlet, it will create objects with the implementation classes of these interfaces, and then pass them to the servlet program. In this case, the developers do not know which implementation classes of the request and response interfaces written by the server manufacturer are? In the program, you can only get the objects provided by the server manufacturer, so you can only enhance these objects by using the decorator design pattern.

  1. First, see what interfaces or parent classes the enhanced object inherits, and write a class to inherit these interfaces or parent classes.   2. Define a variable in the class. The variable type is the type of object to be enhanced.   3. Define a constructor in the class to receive the object to be enhanced.   4. Cover the methods to be enhanced and write enhanced code.

The servlet API provides a default implementation class httpservletrequestwrapper of the decorator design pattern of the request object. The httpservletrequestwrapper class implements all the methods in the request interface, but the internal implementation of these methods only calls the corresponding methods 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.

Write a filter characterencoding filter for handling Chinese garbled code. The code is as follows: characterencoding filter filterconfig filterconfig = string defaultcharset = "UTF-8" filterchain chain) HttpServletRequest request = httpservletresponse response = string charset = filterconfig getInitParameter("charset" (charset== charset = response.setContentType("text/html;charset="+ MyCharacterEncodingRequest requestWrapper = init(FilterConfig filterConfig) . filterConfig = MyCharacterEncodingRequest . request = String value= (value== (!.request.getmethod(). Equalsignorecase ("get"} value = string (value. GetBytes ("iso8859-1"),}} on the web Configure characterencodingfilter in XML file: characterencodingfilter > me gacl. web. filter. Characterencoding Filter > characterencoding filter write JSP test page as follows: <% @ page language = "Java" pageencoding = "UTF-8"% > <% -- import JSTL Tag Library --% > <% @ taglib URI=“ http://java.sun.com/jsp/jstl/core "Prefix =" C "% > use character filter < a href =" "" https://www.jb51.cc/tag/jiejue/ " target="_ Blank "class =" Keywords "> solve < / a > < a href =" " https://www.jb51.cc/tag/jiejue/ " target="_ Blank "class =" Keywords "> solve the problem of < a href =" "under < / a > get and post requests https://www.jb51.cc/tag/zhongwen/ " target="_ blank" class="keywords "> Chinese < / a > garbled code problem <% -- use the C: URL tag to build the URL. The built URL is stored in the servletdemo1 variable -- > <% -- the attached Chinese parameter of the built URL. The parameter name is: username, and the value is: lonely Wolf -- > <% -- access by get -- > <% -- submit the form by post -- >% > User Name: write servletdemo1 servletdemo1 s to process user requests tring username = request. Getparameter ("username" string method = printwriter out = out. Write ("request method:" + out. Write ("received parameter:" +} in this way, the problem of Chinese garbled code can be solved in both get request and post request. Write an HTML escape filter with the code as follows: htmlfilter filterchain chain) HttpServletRequest request = HttpServletResponse response = MyHtmlRequest myrequest = init(FilterConfig filterConfig) MyHtmlRequest . request = String value = (value == (message == content[] = message.getChars(0,message.length(),content,0 StringBuffer result = StringBuffer(content.length + 50 ( i = 0; i < content.length; i++ '<' result.append("<" '>' result. append(">" '&' result. append("&" ' "'result. Append (" & quote; "} configure htmlfilter htmlfilter > me.gacl.web.filter.htmlfilter > htmlfilter in web.xml file to write JSP test page, as follows: <% @ page language =" Java "=" Java. Util. * "pageencoding =" UTF-8 " "% > HTML filter test @ h_464_301 @ write servletdemo2 servletdemo2 string message = request. Getparameter (" message "response. Getwriter(). Write (" your last message was: "+} in this way, all HTML tags are escaped and output. Write a sensitive character filter with the following code: dirtyfilter filterconfig config = init (filterconfig filterconfig) .config = FilterChain chain) HttpServletRequest request = HttpServletResponse response = DirtyRequest dirtyrequest = List List dirtyWords = ArrayList String dirtyWordPath = config. getInitParameter("dirtyWord" InputStream inputStream = InputStreamReader is = is = InputStreamReader(inputStream,"UTF-8" } BufferedReader reader = ((line = reader.readLine())!= ) { } DirtyRequest List dirtyWords = . Request = string value = (value = = system. Out. Println ("the content contains sensitive words:" + dirtyword + ", which will be replaced by * * * *" value = value. Replace (dirtyword, "* * * *) }On the web Configure dirtyfilter > me. XML file gacl. web. filter. DirtyFilter > dirtyWord /WEB-INF/DirtyWord. Txt dirtyfilter when the content filled in by the user contains some sensitive characters, these sensitive characters will be replaced in the dirtyfilter filter. If we combine the above three filters: characterencoding filter, htmlfilter and dirtyfilter, we will wrap the request object three times. The getparameter method of the request object is rewritten three times, which greatly enhances the function of the getparameter method, and can solve Chinese garbled code and HTML tag escape at the same time, Sensitive characters filter these requirements. In actual development, the above three filters can be combined into one, so that the combined filter has the functions of solving Chinese garbled code, HTML tag escape and sensitive character filtering, for example: advancedfilter filterconfig filterconfig = string defaultcharset = "UTF-8" init (filterconfig filterconfig) filterConfig = FilterChain chain) HttpServletRequest request = HttpServletResponse response = String charset = filterConfig. getInitParameter("charset" (charset== charset = response.setContentType("text/html;charset="+ AdvancedRequest requestWrapper = AdvancedRequest List dirtyWords = .request = String value= (value== (!.request.getmethod(). equalsIgnoreCase("get" value= } value = String(value.getBytes("ISO8859-1"), value= System. out. Println ("the content contains sensitive words:" + dirtyword + ", which will be replaced by * * * *" value = value. Replace (dirtyword, "* * * *"} (value = = content [] = value. Getchars (0, value. Length()), 0 StringBuffer result = StringBuffer (content. Length + 50 (I = 0; I < content. Length; I + + '<' result. Append ("& lt;" >) ' result. append(">" '&' result. append("&" ' "' result.append(""" List List dirtyWords = ArrayList String dirtyWordPath = filterConfig.getInitParameter("dirtyWord" InputStream inputStream = InputStreamReader is = is = } BufferedReader reader = ((line = reader.readLine())!= ) { } }On the web Configure advancedfilter in XML file advancedfilter > me gacl. web. filter. AdvancedFilter > charset UTF-8 dirtyWord /WEB-INF/DirtyWord. Txt advancedfilter advancedfilter also has the functions of solving Chinese garbled code, escaping HTML tags in the content, and filtering sensitive characters in the content. The default implementation class httpservletresponsewrapper of the decorator design pattern of the response object is provided in the servlet API. The httpservletresponsewrapper class implements all methods in the response interface, but the internal implementation of these methods only calls the corresponding methods of the wrapped response object, To avoid the need for users to implement all methods in the response interface when enhancing the response object. Apply the httpservletresponsewrapper object to compress the response body content. Specific idea: pass a custom response object to the target page through the filter. In the customized response object, override the getoutputstream method and getwriter method so that when the target resource calls this method to output the page content, it will get our customized ServletOutputStream object. In our custom servletouputstream object, rewrite the write method to write the written data to a buffer. After the page is output, the data written out by the page can be obtained in the filter, so we can call gzipouptstream to compress the data and then write it to the browser, so as to complete the response positive file compression function. Write a compression filter with the following code: gzipfilter HttpServletRequest request = httpservletresponse response = bufferresponse myresponse = out [] = system out. Println ("original size:" + bytearrayoutputstream bout = gzipoutputstream bout = gzip [] = system. Out. Println ("compressed size:" + response. Setheader ("content encoding", "gzip" init (filterconfig filterconfig) bufferresponse bytearrayoutputstream bout = Response = ServletOutputStream getoutputstream() printwriter getwriter() PW = printwriter (outputstreamwriter (bout), (PW! = (bout! =} myserveletoutputstream. Bout = write (b)} on the web Configure compression filter in XML: configure compression filter gzipfilter > me gacl. web. filter. GzipFilter > GzipFilter *. jsp FORWARD REQUEST GzipFilter *. js GzipFilter *. css GzipFilter *. HTML 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 file, so as to reduce the pressure of the database and improve the response speed of the system. Write a filter for cached data, The code is as follows: webresourcecachedfilter map [] > map = HashMap [] > init (filterconfig filterconfig) filterchain chain) HttpServletRequest request = httpservletresponse response response = string URI = B [] = (b! = string webresourcehtmlstr = bufferresponse myresponse = out [] = bufferresponse bytearrayoutputstream bout = bytearrayoutputstream() Response = ServletOutputStream getoutputstream() printwriter getwriter() PW = printwriter (outputstreamwriter (bout), (PW! =} myserveletoutputstream myserveletoutputstream (bytearrayoutputstream bout) {. Bout = write (b)} on the web Configure web resource cache filter in XML: web resource cache filter webresourcecachedfilter > me gacl. web. filter. WebResourceCachedFilter > WebResourceCachedFilter /login. jsp /test. jsp /test2. JSP 3.3. Prohibit the browser from caching all dynamic pages. There are three HTTP response header fields that can prohibit the browser from caching the current page. Their example codes in the servlet are as follows: 1 response setDateHeader("Expires",-1); 2 response. setHeader("Cache-Control","no-cache"); 3 response. setHeader("Pragma","no-cache"); Not all browsers can fully support the above three response headers, so it is best to use the above three response headers at the same time. Expires header: the value is the GMT time value. A value of - 1 means that the browser does not cache the page. The cache control response header has two common values: no cache means that the browser does not cache the current page. Max age: XXX refers to XXX seconds when the browser caches the page. NoCacheFilter FilterChain chain) HttpServletRequest request = HttpServletResponse response = response. setDateHeader("Expires",-1 response.setHeader("Cache-Control","no-cache" response.setHeader("Pragma","no-cache" init(FilterConfig filterConfig) }   web. The configuration in the XML file is as follows: nocachefilter > me gacl. web. filter. NoCacheFilter > NoCacheFilter *. JSP 3.4. Control the static resources in the browser cache page. Some dynamic pages refer to some pictures or CSS files to modify the page effect. These pictures and CSS files often do not change. Therefore, in order to reduce the pressure of the server, you can use filter to control the browser cache these files to improve the performance of the server. CacheFilter FilterChain chain) HttpServletRequest request = HttpServletResponse response = String uri = String ext = uri. substring(uri.lastIndexOf(".")+ 1 String time = (time!= t = Long.parseLong(time)*3600*1000 response. setDateHeader("expires",System.currentTimeMillis() + init(FilterConfig filterConfig) . filterConfig

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>