Javaweb Back < 12 > filter garbled, non-cached, dirty language, tagging, automatic login, full-station compression filter

Source: Internet
Author: User
Tags base64 md5 encryption

First, what is the filter? What do you got?

1, filter belongs to the servlet specification, from the 2.3 version began to have.

2, filter is the content of the access to filter (interception). Filter requests and responses using filters

Ii. preparation of steps and implementation process

1. Coding steps:

A, write a class: Implement Javax.servlet.Filter interface

public class FilterDemo1 implements Filter {public FilterDemo1 () {System.out.println ("default constructor method called");} Each time a user accesses a filtered resource, the method is called by the server to implement filtering public void DoFilter (ServletRequest request, Servletresponse Response,filterchain Chain) throws IOException, servletexception {System.out.println ("FilterDemo1 before Filtering");//interception of requests, code written in this chain.dofilter ( request, response);//release//intercept the response, the code is written in this System.out.println ("FilterDemo1 after performing the filter");} public void Destroy () {System.out.println ("Call Destruction Method");} public void init (Filterconfig filterconfig) throws Servletexception {System.out.println ("Call initialization Method");}}

B. Configure Web. XML to specify the resources that need to be filtered. (Quite similar to the configuration of the servlet)

2, the implementation process of the filter (life cycle)

Life cycle:

Birth: An instance of a filter is instantiated and initialized when the application is loaded.

Survival: Consistent with the life cycle of the application. In memory is a singleton. For access to resources within the interception range, each access calls void DoFIlter (Request,response.chain) for interception.

Death: The app is uninstalled.

Third, Series filter

One filter followed by another filter. Order of execution according to the order of Web. xml

Discretionary access will be directly FilterDemo2 to perform FILTERDEMO3.

Will output:

FilterDemo2 ago

FilterDemo3 ago

Execute content

After FilterDemo3

After FilterDemo2

Iv. case: 1. Garbled filter to resolve request parameters (POST) and response output
Filter to resolve POST request parameters and response encoding issues public class Setcharacterencodingfilter implements filter {private Filterconfig Filterconfig ;p ublic void init (Filterconfig filterconfig) throws servletexception {this.filterconfig = Filterconfig;} public void DoFilter (ServletRequest request, Servletresponse Response,filterchain chain) throws IOException, servletexception {String encoding = filterconfig.getinitparameter ("encoding");//The user may have forgotten to configure the parameter if (encoding==null) { encoding = "UTF-8";//Default code}request.setcharacterencoding (encoding);// Can only solve the Chinese problem of Post request parameter response.setcharacterencoding (encoding);//output stream encoding Response.setcontenttype ("text/html;charset=" + encoding);//output stream encoding, notifying the client should use the encoding Chain.dofilter (request, response);} public void Destroy () {}}

Write the encoding type in the filter parameter

2, dynamic resources do not cache the filter

SERVLET/JSP: Do not cache dynamic resources.

Here's how to convert ServletRequest and servletresponse to HttpServlet to avoid errors

HttpServletRequest request = null;  HttpServletResponse response = null;try{Request  = (httpservletrequest) req; Response = (httpservletresponse) resp;
}catch (Exception e) {throw new RuntimeException ("Not-http Request or Response");}

Control dynamic resource do not cache filter public class Nocachefilter implements filter {public void init (Filterconfig filterconfig) throws servletexception {}public void DoFilter (ServletRequest req, servletresponse resp,filterchain chain) throws IOException, servletexception {//httpservletrequest request = (httpservletrequest) req;//httpservletresponse response = ( HttpServletResponse) resp;   Do not use this method httpservletrequest request = null; HttpServletResponse response = Null;try{request  = (httpservletrequest) Req;response = (HttpServletResponse) resp;} catch (Exception e) {throw new RuntimeException ("Not-http Request or Response");} Response.setheader ("Expires", "1"), Response.setheader ("Cache-control", "No-cache"), Response.setheader ("Pragma", "No-cache"); Chain.dofilter (request, response);} public void Destroy () {}}

Dynamically filters out Servlets and JSPs

3, static resources to control the cache time filter
Control cache time for static resources public class Staticresourcesneedcachefilter implements Filter {private Filterconfig Filterconfig;public void init (Filterconfig filterconfig) throws servletexception {this.filterconfig = Filterconfig;} public void DoFilter (ServletRequest req, servletresponse resp,filterchain chain) throws IOException, Servletexception { HttpServletRequest request = null; HttpServletResponse response = Null;try{request = (httpservletrequest) Req;response = (HttpServletResponse) resp;} catch (Exception e) {throw new RuntimeException ("Not-http Request or Response");} Long time = 0;//cached//suffix according to the URI address requested by the User:/day19_00_filter/1.htmlstring uri = Request.getrequesturi (); String exname = uri.substring (Uri.lastindexof (".") +1); if ("html". Equals (Exname)) {String value = filterconfig.getinitparameter ("html");//hour time = Long.parselong (value) *60*60*1000;} if ("CSS". Equals (Exname)) {String value = Filterconfig.getinitparameter ("CSS");//hour time = Long.parselong (value) *60*60 *1000;} if ("JS". Equals (Exname)) {String value = FilTerconfig.getinitparameter ("JS");//hour time = Long.parselong (value) *60*60*1000;}  Response.setdateheader ("Expires", System.currenttimemillis () +time); Expires Control Time Chain.dofilter (request, response);} public void Destroy () {}}

4,//* user Automatic login filter:

Use of MD5 encryption

BASE64 encoding: Very Important

Write

Automatic login filter public class Autologinfilter implements filter {private Businessservice s = new Businessserviceimpl ();p ublic voi D init (Filterconfig filterconfig) throws servletexception {}public void DoFilter (ServletRequest req, servletresponse Resp,filterchain chain) throws IOException, servletexception {httpservletrequest request = null; HttpServletResponse response = Null;try{request = (httpservletrequest) Req;response = (HttpServletResponse) resp;} catch (Exception e) {throw new RuntimeException ("Not-http Request or Response");} HttpSession session = Request.getsession ();//Determine if the user has logged in: Just do not login user Suser = (user) Session.getattribute ("User"); Suser==null) {//Find Logininfo Cookie: Just find the cookie cs[] = request.getcookies (); for (int i=0;cs!=null&&i< cs.length;i++) {if ("Logininfo". Equals (Cs[i].getname ())) {//Solve the user name (BASE64) and password (MD5) String Usernamepassword = Cs[i]. GetValue (); String username = Usernamepassword.split ("_") [0];//base64 encoded string password = Usernamepassword.split ("_") [1];// MD5 after encryption//call service againThe second authentication is correct for user user = S.login (securityutil.base64decode (username), password);//via: Login. Set the login token if (user!=null) {session.setattribute ("user", user) in HttpSession;}}} Chain.dofilter (request, response);} public void Destroy () {}}

Five, the filter configuration details

Vi. consolidation of decorative design patterns

First, decoration

1. Write a class that implements the same interface as the wrapper class (the database-driven implementation of connection). (Enables the same behavior for this class and the drive implementation of the database)

2. Define a variable that references the instance of the wrapped class.

3. Define the constructor method and pass in the instance of the wrapped class.

4, for the method to rewrite, write your own code can.

5. For methods that do not require rewriting, call the corresponding method of the original object.

Second, the decorative variant (BufferedReader itself is the packaging class, the packaging of reader. LineNumberReader, the packaging of BufferedReader, or his sub-category)

1, write a class, inheritance is already a wrapper class class.

2. Define a variable that references the instance of the wrapped class.

3. Define the constructor method and pass in the instance of the wrapped class.

4, covering the need to rewrite the method

Vii. case: 1, solve the whole station Chinese garbled filter

Solved the problem of post garbled problem here add get

1. Define a class encodinghttpservletrequest inherit httpservletrequestwrapper before the wrapper to get the method you want

2. Rewrite the Httpservletrequestwrapper getparameter method.

3. Use the super.getcharacterencoding () encoding to return the value of the get passed in

You can get the proper encoding if you use the Get method

public class Setcharacterencodingfilter implements Filter {private filterconfig filterconfig;public void Init ( Filterconfig filterconfig) throws servletexception {this.filterconfig = Filterconfig;} public void DoFilter (ServletRequest req, servletresponse resp,filterchain chain) throws IOException, Servletexception { HttpServletRequest request; HttpServletResponse response;try{request = (httpservletrequest) Req;response = (HttpServletResponse) resp;} catch (Exception e) {throw new RuntimeException ("Non-http Request or Response");} String encoding = filterconfig.getinitparameter ("encoding");//The user may have forgotten to configure the parameter if (encoding==null) {encoding = "UTF-8";// The default encoding}request.setcharacterencoding (encoding),//can only resolve the POST request parameters of the Chinese Problem response.setcharacterencoding (encoding); Output stream encoding Response.setcontenttype ("text/html;charset=" +encoding);//output stream encoding notifies the client of the encoding that should be used Encodinghttpservletrequest Erequest = new Encodinghttpservletrequest (request); Chain.dofilter (erequest, response);} public void Destroy () {}}class encodinghttpservletrequest exTends Httpservletrequestwrapper{public encodinghttpservletrequest (HttpServletRequest request) {super (request); public string GetParameter (string name) {String value = Super.getparameter (name); if (value==null) return value;// Just get the way if ("get". Equalsignorecase (Super.getmethod ())) {try {value = new String (value.getbytes ("iso-8859-1"), Super.getcharacterencoding ());} catch (Unsupportedencodingexception e) {e.printstacktrace ();}} return value;}}
2, filter dirty words filter

1. New Dwhttpservletrequest class inherits Httpservletrequestwrapper,

2. Packaging GetParameter Hair Method filter Dirty Words

3. When the content is executed, the request is dwhttpservletrequest, so the method used is Dwhttpservletrequest getparameter.

public class Dirtywordsfilter implements Filter {public void init (filterconfig Filterconfig) throws servletexception {}public void DoFilter (ServletRequest req, servletresponse resp,filterchain chain ) throws IOException, servletexception {httpservletrequest request; HttpServletResponse response;try{request = (httpservletrequest) Req;response = (HttpServletResponse) resp;} catch (Exception e) {throw new RuntimeException ("Non-http Request or Response");} Dwhttpservletrequest dwrequest = new Dwhttpservletrequest (request); Chain.dofilter (dwrequest, response);} public void Destroy () {}}class dwhttpservletrequest extends httpservletrequestwrapper{private string[] STRs = {"Beast", "Beast" , "Silly B", "Zhang Yinpeng"};p ublic dwhttpservletrequest (HttpServletRequest request) {super (request); public string GetParameter (string name) {String value = Super.getparameter (name); if (value==null) return value;for ( String s:strs) {value = Value.replace (S, "* *");} return value;}} 
3. HTML tag Filter

Methods and the first 2 kinds of similar

public class Htmlfilter implements Filter {public void init (Filterconfig filterconfig) throws servletexception {}public vo ID DoFilter (servletrequest req, servletresponse resp,filterchain chain) throws IOException, Servletexception { HttpServletRequest request; HttpServletResponse response;try{request = (httpservletrequest) Req;response = (HttpServletResponse) resp;} catch (Exception e) {throw new RuntimeException ("Non-http Request or Response");} Htmlhttpservletrequest hrequest = new Htmlhttpservletrequest (request); Chain.dofilter (hrequest, response);} public void Destroy () {}}class htmlhttpservletrequest extends Httpservletrequestwrapper{public htmlhttpservletrequest (HttpServletRequest request) {super (request);} public string GetParameter (string name) {String value = Super.getparameter (name); if (value==null) return value;value = Htmlfilter (value);//escape character return value;}        private string Htmlfilter (String message) {if (message = = NULL) return (NULL); Char content[] = new Char[message.lenGth ()];        Message.getchars (0, Message.length (), content, 0);        StringBuffer result = new StringBuffer (content.length + 50); for (int i = 0; i < Content.length, i++) {switch (Content[i]) {case ' < ': ResU                Lt.append ("<");            Break                Case ' > ': Result.append (">");            Break                Case ' & ': Result.append ("&");            Break                Case ' ': Result.append ("" ");            Break            Default:result.append (Content[i]); }} return (Result.tostring ());}}

4,//* full-station compression filter (difficult)

public class Gzipfilter implements Filter {public void init (Filterconfig filterconfig) throws servletexception {}public vo ID DoFilter (servletrequest req, servletresponse resp,filterchain chain) throws IOException, Servletexception { HttpServletRequest request; HttpServletResponse response;try{request = (httpservletrequest) Req;response = (HttpServletResponse) resp;} catch (Exception e) {throw new RuntimeException ("Non-http Request or Response");} Gziphttpservletresponse gresponse = new Gziphttpservletresponse (response); Chain.dofilter (request, gresponse);// The target resource executes after execution: to compress byte b[] = Gresponse.getbytes (),//To get the original data for the encoded key point System.out.println ("Pre-Compression size:" +b.length);// Determine if the customer supports gzip compression string acceptencoding = Request.getheader ("accept-encoding"); if (acceptencoding!=null&& Acceptencoding.contains ("gzip")) {//support bytearrayoutputstream out = new Bytearrayoutputstream (); Gzipoutputstream gout = new Gzipoutputstream (out); Gout.write (b); Gout.close (); b = Out.tobytearray ();// Compressed data System.out.println ("Compressed size:" +b.length);//Tell the browser compression mode Response.setheader ("content-encoding", "gzip"); Response.setcontentlength (b.length);//Tell the client, the length of the body} Response.getoutputstream (). write (b);} public void Destroy () {}}class Gziphttpservletresponse extends Httpservletresponsewrapper{private Bytearrayoutputstream BAOs = new Bytearrayoutputstream ()///store intercepted data private printwriter PW = Null;public Gziphttpservletresponse (HttpServletResponse response) {super (response);} Intercept output data: Put into BAOs public servletoutputstream Getoutputstream () throws IOException {return new Myservletoutputstream ( BAOs);} Character stream: Intercept put into BAOs public printwriter getwriter () throws IOException {pw = new PrintWriter (new OutputStreamWriter (BAOs, Super.getcharacterencoding ())); return PW;} Gets the intercepted data public byte[] GetBytes () {try {if (pw!=null) {pw.close ();} Baos.flush ();} catch (IOException e) {e.printstacktrace ();} return Baos.tobytearray ();}} Class Myservletoutputstream extends Servletoutputstream{private bytearrayoutputstream baos;public Myservletoutputstream (Bytearrayoutputstream BAOs) {THis.baos = BAOs;} public void Write (int b) throws IOException {baos.write (b);}}

Javaweb Back < 12 > filter garbled, non-cached, dirty language, tagging, automatic login, full-station compression filter

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.