Use of Java Filters (filter)

Source: Internet
Author: User

Request.setcharacterencoding ("Utf-8"); Response.setcontenttype ("Text/html;charset=utf-8");

This is the code that sets the character encoding in the servlet, but usually there is more than one servlet, so we need to write the above code in every servlet, so it's not only cumbersome, but confusing.

So when we execute the same code in more than one servlet, we can usually use a filter to help us do the following:

Filter:

If you want to use a filter, you first need to implement the filter class and rewrite the three required methods:

Importjavax.servlet.*;ImportJavax.servlet.annotation.WebFilter;Importjava.io.IOException; @WebFilter (FilterName= "TestFilter2", Urlpatterns = "/*") Public classTestFilter2ImplementsFilter { Public voiddestroy () {} Public voidDoFilter (ServletRequest req, Servletresponse resp, filterchain chain)throwsservletexception, IOException {chain.dofilter (req, resp); }     Public voidInit (filterconfig config)throwsservletexception {}}

Init method: The container is automatically called when the current filter is created ;

Destroy method: The container is automatically called when the current filter is destroyed

Dofilter method: The main code of the filter is written in this place

1 @WebFilter (filtername = "TestFilter2", Urlpatterns = "/*")

This line of code means to add an annotation that does not need to be registered with the Web.

Where FilterName represents the name of the filter, and the latter urlpatterns represents the filtered path/* representing all paths, which means that the filter is accessed first when all paths are accessed.

Chain.dofilter (req, resp);

This line of code represents the call to other filters if there are other filters, but be aware that this line of code must be written on the last side of the Dofilter method

1  Public voidDoFilter (ServletRequest req, Servletresponse resp, filterchain chain)throwsservletexception, IOException {2         //This will be done at the time each servlet executes.3HttpServletRequest request =(httpservletrequest) req;4HttpServletResponse response =(HttpServletResponse) resp;5 6Request.setcharacterencoding ("Utf-8");7Response.setcontenttype ("Text/html;charset=utf-8");8 9         //because there may be more than one filter, all the filters need to be executedTen         //Note that this line of code must be written to the last One Chain.dofilter (req, resp); A}

Where 3-7 lines of code is the set encoding

Since the dofilter passed in by default is the ServletRequest object and the character set is in httpservetrequest, we need to force a conversion.

After the conversion, we can set it up.

Here is a code for my other test filter:

1 Importjavax.servlet.*;2 ImportJavax.servlet.annotation.WebFilter;3 Importjavax.servlet.http.HttpServletRequest;4 ImportJavax.servlet.http.HttpServletRequestWrapper;5 ImportJavax.servlet.http.HttpServletResponse;6 Importjava.io.IOException;7 Importjava.io.UnsupportedEncodingException;8 9 /**Ten * Urlpatterns represents the need to filter those paths down here for * representing all paths that need to enter this filter One  */ A@WebFilter (filtername = "Testfilter", Urlpatterns = "/*") -  Public classTestfilterImplementsFilter { -      Public voiddestroy () { the     } -  -     /** - * Any code written here will be executed before the servlet JSP is executed. +      */ -      Public voidDoFilter (ServletRequest req, Servletresponse resp, filterchain chain)throwsservletexception, IOException { +         //This will be done at the time each servlet executes. AHttpServletRequest request =(httpservletrequest) req; atHttpServletResponse response =(HttpServletResponse) resp; -  -Request.setcharacterencoding ("Utf-8"); -Response.setcontenttype ("Text/html;charset=utf-8"); -  -         //because there may be more than one filter, all the filters need to be executed in         //Note that this line of code must be written to the last - Chain.dofilter (req, resp); to     } +  -      Public voidInit (filterconfig config)throwsservletexception { the  *     } $ Panax Notoginseng     //implement the Get method auto-transcoding by overriding the GetParameter method -     classMywrapperextendshttpservletrequestwrapper{ the         Privatehttpservletrequest request; +          PublicMywrapper (HttpServletRequest request) { A             Super(request); the              This. Request =request; +         } -  $ @Override $          Publicstring GetParameter (string name) { -String value = This. Request.getparameter (name); -             if(Value = =NULL){ the                 return NULL; -             }Wuyi  the             //if it was submitted by the Get method . -             if( This. Request.getmethod (). Equalsignorecase ("Get")){ Wu                 Try { -                     //to Transcode AboutValue =NewString (Value.getbytes ("iso-8859-1"), "Utf-8"); $}Catch(unsupportedencodingexception e) { - e.printstacktrace (); -                 } -             } A  +             //Shielded angle brackets &gt; &lt; theValue = Value.replace (">", "&gt;"); -Value = Value.replace ("<", "&lt;"); $  the             returnvalue; the         } the     } the}

Use of Java Filters (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.