L--java Web Filter

Source: Internet
Author: User

What is Filter

Filter is a filter under Java that enables the filtering of Java Web Program clients and server-side messages, which can be pre-processed before the request is accepted by the servers, or before the client accepts response. The response is processed.

The use of filter is very flexible, between the "chain" to the client and the service side, when needed can be configured between the client and the server, can be removed when not needed. Filter can also set its filtering on which pages are sent to or from which pages, which is a crosscutting programming, pluggable. The general process of filter execution is as follows

To implement the filter-related functions, you need to implement the filter interface under the Javax.servlet.jar package, which has three methods, namely Init, Dofilter,destory method, put the code that needs to perform some functions in the Dofilter method

A filter handles a JSP

The following example sets the character encoding for all JSP pages

 PackageCom.tgb.drp.util.filter;Importjava.io.IOException;ImportJavax.servlet.Filter;ImportJavax.servlet.FilterChain;ImportJavax.servlet.FilterConfig;Importjavax.servlet.ServletException;Importjavax.servlet.ServletRequest;ImportJavax.servlet.ServletResponse;/*** Uniform processing of character sets using filter **/ Public classCharsetencodingfilterImplementsFilter {PrivateString encodestring; //Filter Logoff Method@Override Public voiddestroy () {}//filter to implement the function@Override Public voidDoFilter (servletrequest request, servletresponse response, Filterchain chain)throwsIOException, servletexception {System.out.println ("Begin"); //Set character setsrequest.setcharacterencoding (encodestring); //continue down, if there is another filter that continues to call the other filter, no message is sent to the server or clientChain.dofilter (request, response); System.out.println ("End"); }        //Initialize Method@Override Public voidInit (Filterconfig filterconfig)throwsservletexception {//Encodestring=filterconfig.getinitparameter ("Encoding"); }}

After writing the filter class, you need to set up in the configuration file for those request and response filter processing, this example set all the JSP page processing, under the Web-app node of Web. XML, after configuration, can be tested.

    <Filter>        <Filter-name>Charsetencodingfilter</Filter-name>        <Filter-class>Com.tgb.drp.util.filter.CharsetEncodingFilter</Filter-class>        <Init-param>            <Param-name>Encoding</Param-name>            <Param-value>GBK</Param-value>        </Init-param>    </Filter>    <filter-mapping>        <Filter-name>Charsetencodingfilter</Filter-name>        <Url-pattern>*.jsp</Url-pattern>    </filter-mapping>
Multiple filter processing a JSP page

If you want to implement multiple filter to process the same JSP page, for example, you need to set the character encoding, there is a need to verify the identity, only after writing a good response to the filter to continue to configure in Web. Xml. We continue with the above example, and then write an authentication filter, named Authentionfilter, as follows

 PackageCom.tgb.drp.util.filter;Importjava.io.IOException;ImportJavax.servlet.Filter;ImportJavax.servlet.FilterChain;ImportJavax.servlet.FilterConfig;Importjavax.servlet.ServletException;Importjavax.servlet.ServletRequest;ImportJavax.servlet.ServletResponse;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;Importjavax.servlet.http.HttpSession; Public classAuthenticationfilterImplementsFilter {@Override Public voiddestroy () {} @Override Public voidDoFilter (servletrequest request, servletresponse response, Filterchain chain)throwsIOException, servletexception {//Controlling user access rightsHttpServletRequest req=(httpservletrequest) request; HttpServletResponse Res=(httpservletresponse) response; HttpSession Session=req.getsession (); if(Session.getattribute ("User_info")! =NULL) {Chain.dofilter (request, response); }Else{res.sendredirect (Req.getcontextpath ()+ "/error.html"); }} @Override Public voidInit (Filterconfig filterconfig)throwsservletexception {}}

Then the configuration file continues with the following configuration, the code is as follows:

<?XML version= "1.0" encoding= "UTF-8"?><Web-appversion= "2.4"xmlns= "HTTP://JAVA.SUN.COM/XML/NS/J2EE"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "Http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">      <welcome-file-list>        <Welcome-file>Index.html</Welcome-file>    </welcome-file-list>     <Filter>        <Filter-name>Charsetencodingfilter</Filter-name>        <Filter-class>Com.tgb.drp.util.filter.CharsetEncodingFilter</Filter-class>        <Init-param>            <Param-name>Encoding</Param-name>            <Param-value>GBK</Param-value>        </Init-param>    </Filter>    <filter-mapping>        <Filter-name>Charsetencodingfilter</Filter-name>        <Url-pattern>*.jsp</Url-pattern>    </filter-mapping>        <Filter>        <Filter-name>Authenticationfilter</Filter-name>        <Filter-class>Com.tgb.drp.util.filter.AuthenticationFilter</Filter-class>    </Filter>    <filter-mapping>        <Filter-name>Authenticationfilter</Filter-name>        <Url-pattern>*.jsp</Url-pattern>    </filter-mapping>        <Session-config>        <Session-timeout>60</Session-timeout>    </Session-config></Web-app>

L--java Web Filter

Related Article

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.