Javaweb Filter Use

Source: Internet
Author: User

Filter Learning
What is 1Filter: a filter abbreviation
What does 2Filter do: In the filter you get request and response objects that represent user requests and responses, so in programming you can use the decorator (adorner) mode to wrap the request, Response object, and then wrap the object To target resources to achieve some special needs.
Example: To cite an inappropriate example: for example, when the person we like calls us, we want the phone to provide a different ringtone,
Let me tell you who called me so I wouldn't have to take out my cell phone to know who called me.
3Filter Operation Principle Analysis
Such as:
 

Description of the 3Filter interface:
①Filterconfig Interface: When the user configures the filter, it can use <init-param> to configure some initialization parameters for the filter, when the Web container instantiates the filter object and calls its Init method. The Filterconfig object that encapsulates the filter initialization parameter is passed in. As a result, when writing the filter, the developer can obtain: by Filterconfig the object's method .

String getfiltername (): Gets the name of the filter.
String Getinitparameter (string name): Returns the value of the initialization parameter for the name specified in the deployment description. Returns null if it does not exist.
Enumeration Getinitparameternames (): Returns an enumeration collection of the names of all initialization parameters for the filter.
Public ServletContext Getservletcontext (): Returns a reference to the Servlet context object.

②filterchian interface: In a Web application, you can develop and write multiple filter combinations called the filter chain.
The Web server decides which filter to call first, based on the order in which the filter is registered in the Web. xml file, and when the Dofilter method of the first filter is called, it creates a Filterchain object representing the filter chain to that party Method. In the Dofilter method, if the developer calls the Dofilter method of the Filterchain object, the Web server checks to see if there is a filter in the Filterchain object, and if so, the 2nd filter, if not, The target resource (the resource of the URL) is invoked.

3Filter How to use:
Steps to use:

1 Customizing the filter and implementing the built-in filter interface
2 Carbon dofilter () method, in which we handle the logic we need
3 If there are other filters, call Filterchian's Dofilter () method
4 If the return page is to use response
5 Register filter, configure filter to intercept what kind of request
Example of a 4JAVAWEB filter code
① Custom Filter:

 PackageCom.filter.demo;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; Public classCharacterencodingfilterImplementsfilter{filterconfig filterconfig=NULL; String characterencoding= "UTF-8";    String str; @Override Public voiddestroy () {//TODO auto-generated Method Stub} @Override Public voidDoFilter (ServletRequest arg0, Servletresponse arg1, Filterchain arg2)throwsIOException, servletexception {httpservletrequest request=(httpservletrequest) arg0; HttpServletResponse Response=(HttpServletResponse) arg1; System.out.println ("Intercept to request."); System.out.println ("Encoded as---->" +str); if(str==NULL) {System.out.println (); STR=characterencoding; }        //2 Setting the encodingrequest.setcharacterencoding (str);        Response.setcharacterencoding (str); Request.setattribute ("Name", "Jere"); System.out.println ("Pre-execution--->name=" +request.getattribute ("name")); //returns the next filterArg2.dofilter (request, response); System.out.println ("After execution--->name=" +request.getattribute ("name")); } @Override Public voidInit (Filterconfig arg0)throwsservletexception {System.out.println ( This. GetClass (). GetName () + "Filter started-----"); //gets the parameters of the startupfilterconfig=arg0; STR=filterconfig.getinitparameter ("name"); }}

Custom servlet:

 PackageCom.filter.demo;Importjava.io.IOException;Importjavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;ImportOrg.apache.jasper.tagplugins.jstl.core.Out;/*** Servlet Implementation class Filterservlet*/ Public classFilterservletextendsHttpServlet {Private Static Final LongSerialversionuid = 1L; /**     * @seeHttpservlet#httpservlet ()*/     PublicFilterservlet () {Super(); //TODO auto-generated Constructor stub    }    /**     * @seeHttpservlet#doget (httpservletrequest request, httpservletresponse response)*/    protected voidDoget (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {response.getwriter (). Print ("Test"); Request.setattribute ("Name", "Jeremy"); }    /**     * @seeHttpservlet#dopost (httpservletrequest request, httpservletresponse response)*/    protected voidDoPost (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {//TODO auto-generated Method Stub    }}

③ registering the servlet and filter in the Web. xml file
  

 <servlet>    <Description></Description>    <Display-name>Filterservlet</Display-name>    <Servlet-name>Filterservlet</Servlet-name>    <Servlet-class>Com.filter.demo.FilterServlet</Servlet-class>  </servlet>  <servlet-mapping>    <Servlet-name>Filterservlet</Servlet-name>    <Url-pattern>/filterservlet</Url-pattern>  </servlet-mapping>  <Filter>          <Filter-name>Characterencodingfilter</Filter-name>        <Filter-class>Com.filter.demo.CharacterEncodingFilter</Filter-class>        <Init-param>            <Param-name>Name</Param-name>            <Param-value>UTF-8</Param-value>        </Init-param>  </Filter>  <filter-mapping>          <Filter-name>Characterencodingfilter</Filter-name>
<!--can also use Url-pattern-<Servlet-name>Filterservlet</Servlet-name> </filter-mapping>

Page testing

<%@ Page Language="Java"ContentType="text/html; charset=iso-8859-1"pageencoding="iso-8859-1"%><!DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd "><HTML><Head><Metahttp-equiv= "Content-type"content= "text/html; charset=iso-8859-1"><title>Insert Title here</title></Head><Body><ahref= "/filterdemo/filterservlet">Test Filter</a></Body></HTML>

The above is a simple filter example

Javaweb Filter Use

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.