Filter basics, filter

Source: Internet
Author: User

Filter basics, filter
I. Summary

 

Simply put, the function of Filter is to intercept (Tomcat) service (Request, Response) method, get the Request and Response object for processing, then release the control, and continue automatic flow. It uses the idea of "layering.

I personally feel that the root cause is to block the Request and Response objects.MultipleServer resources (Servlet, JSP, and so on) requests and corresponding public settings. Here we emphasize "multiple ". If it is a resource, there is no need to set the Filter, because you only need to set the Request and Response where the resource needs (Before), that is, "set" can be put anywhere, because many requests and responses share many common settings, we extract the commonalities as a layer, which is called Filter. For example:

 

Traditional call:

 

 

Add Filter:

 

 

Ii. FilterChain

 

When several servlets have some identical settings (filtering), while the other servlets have other identical settings ......, Such a Filter cannot complete all the filters. Therefore, multiple filters are required to complete the task together. So the famous FilterChain came out. How can multiple filters in this FilterChain collaborate?

Each Filter has different functions. When a Servlet request arrives, the request will go through the Filter chain one by one and go to the Filter it needs, the Filter will perform the Request and Response operations on it, and then automatically go down after the operation is completed. This is the so-called responsibility chain model.

Each Filter has three methods:

Ø init (FilterConfig filterConfig)

Ø doFilter (ServletRequest request, ServletResponse response, FilterChain chain)

Ø destroy ()

The three methods are executed in sequence (as described below). The execution sequence of multiple filters in a Filter chain is as follows:

  

 

That is, run the code before chain. doFilter () of the first filter ----> code before chain. doFilter () of the second filter ----> ...... ----> The chain of the nth filter. code before doFilter () ----> code in the service () method of the requested servlet --> doGet () or doPost () of the requested servlet () the code in the method ----> the chain of the nth filter. code after doFilter () ----> ...... ----> Code after chain. doFilter () of the second filter ----> code after chain. doFilter () of the first filter.

 

Iii. Main interfaces and Methods

 

First, the Servlet filter API containsThree InterfacesIn the javax. servlet package, these are the Filter interface, FilterChain interface, and FilterConfig interface.Use:

All filters must implement the Filter interface. This interface defines three methods: init (), doFilter (), and destory.

Ø the FilterChain interface is used as a parameter of the doFilter0 method: includofilter (ServletRequest request, ServletResponse response,FilterChainChain)

The FilterConfig interface is used as a parameter for the init () method: init (FilterConfigFilterConfig)

That is, the Filter class will implement the Filter interface, and then use the FilterChain and FilterConfig interfaces in this Filter class. A reference of the filter class is passed to the FilterChain object, allowing the filter to pass control to the next resource in the chain. The FilterConfig object is provided to the filter by the container to allow access to the initialization data of the filter. The following describes the three interfaces and the Methods:

 

Filter Interface

1) public void init (FilterConfig filterConfig) throws ServletException.

When starting to use the servlet filter service, the Web Container calls this method once to prepare a filter for the service. That is, the initialization parameter of the filter is obtained through the FilterConfig object, that is, the information configured in the configuration file. Call doFilter () when you need to use a filter and pass the configuration information.

2)Public voiddoFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletExceptioN

Each filter accepts the current request and response, and the filter in the FilterChain filter chain (should all be qualified) will be executed. In the doFilter method, the filter can do everything it wants to do for requests and responses, collect data by calling their methods, or add new behaviors to objects.

By transmitting the FilterChain parameter of this method, the filter calls chain. doFilter () to send control to the next filter. After this call is returned, the Filter can perform other work on the response at the end of its Filter method. If the filter wants to terminate the request processing or obtain full control over the response, you can redirect the filter to other pages without calling the next filter. When the last filter in the chain calls the chain. doFilter () method, the initial requested Servlet is run.

3) public voiddestroy ()

If all threads in the doFilter () method exit or have timed out, the container calls this method. The server calls destory () to indicate that the filter service has ended.

Resources occupied by the filter.

 

FilterChain Interface

1) public voiddoFilter (ServletRequest request, ServletResponse response) throws java. io. IOException, ServletException

This method is provided to developers by the Servlet container, which is used to call the filter chain of resource requests in sequence. The filter chain is called through FilterChain. If it is the last filter, the next resource is called.

 

FilterConfig Interface

The FilterConfig interface retrieves the Filter Name, initialization parameters, and active Servlet context.

1) public java. lang. StringGetFilterName ()

2) public ServletContextGetServletContex ()

3) public java. lang. StringGetlnitParameter (java. lang. String name)

4) public java. util. EnumerationGetlnitParameterNames ()

 

Iv. Configuration and usage

 

The filter uses the description in the Web application configuration descriptor web. xml file, including <filter>, <filter-mapping>:

 

<Filter>, mainly including:

1) <filter-name> and <f'flter-class> are two required child elements.

2) <icon>, <init-param>, <display-name>, and <description>.

<Filter-name> the sub-element defines the name of a filter. <filter-class> specifies the actual class loaded by the container, the <init-param> sub-element provides initialization parameters for the filter.

 

<Filter-mapping> mainly consists

1) <filter-name>, <servlet-name>, and <url-pattem> subelements.

<Servlet-name> map the filter to one or more servlets. <url-pattem> map the filter to the JSP page of a URL with one or more arbitrary features.

 

Four configuration methods of <url-pattem>:

  

<Filter> <filter-name> CharsetEncodingFilter </filter-name> <filter-class> com. bjpowernode. drp. util. filter. charsetEncodingFilter </filter-class> <init-param> <param-name> encoding </param-name> <param-value> GBK </param-value> </init- param> </filter> <! -- Exact match, no modifier --> <filter-mapping> <filter-name> CharsetEncodingFilter </filter-name> <url-pattern>/servlet/TestServlet </url-pattern> </filter-mapping> <! -- Extension match, which consists of * and extension --> <filter-mapping> <filter-name> CharsetEncodingFilter </filter-name> <url-pattern> *. jsp </url-pattern> </filter-mapping> <! -- Path prefix match, contains a directory and A/* --> <filter-mapping> <filter-name> CharsetEncodingFilter </filter-name> <url-pattern>/servlet/* </url-pattern> </filter-mapping> <! -- Full match, use/* --> <filter-mapping> <filter-name> CharsetEncodingFilter </filter-name> <url-pattern>/* </url-pattern> </filter-mapping>

V. Sample Code:

 

Filter class:
Package com. bjpowernode. drp. util. filter; import java. io. IOException; import javax. servlet. filter; import javax. servlet. filterChain; import javax. servlet. filterConfig; import javax. servlet. servletException; import javax. servlet. servletRequest; import javax. servlet. servletResponse; import org. omg. CORBA. request;/*** use the Filter to agree to process the character set * @ author v-wangzhip */public class CharsetEncodingFilter implements Filter {private String encoding; @ Overridepublic void destroy () {// TODO Auto-generated method stub} @ Overridepublic void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {// System. out. println ("CharsetEncodingFilter ----> begin"); // sets the character set request. setCharacterEncoding (encoding); // continue to run chain. doFilter (request, response); // System. out. println ("CharsetEncodingFilter ----> end") ;}@ Overridepublic void init (FilterConfig filterConfig) throws ServletException {this. encoding = filterConfig. getInitParameter ("encoding"); System. out. println ("encoding ---->" + encoding );}}

 

Web. xml configuration:
  <filter>  <filter-name>CharsetEncodingFilter</filter-name>  <filter-class>com.bjpowernode.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-mapping>  <filter-name>CharsetEncodingFilter</filter-name>  <url-pattern>/servlet/*</url-pattern>  </filter-mapping>

 

Vi. Summary

 

In my opinion, Filter is an intermediate layer that inserts the public items in the request-response into the request-response. Multiple filters form a FilterChain. Each Filter has its own function and can process incoming requests and responses according to certain rules, reflecting the responsibility chain mode. Filter only applies to post requests. It provides a declarative service with pluggable capabilities, that is, it can be enabled or disabled at will.

 


Introduction to jsp filter

The first sessionKey should be in the web. check whether the checkSessionKey configured in the xml file has been obtained. It is possible that the entire parameter is stored on the web later. xml, so you need to judge in the filter.
The second is to retrieve the user corresponding to the checkSessionKey from the session, which should be the information of the current login user.

Who can give me a basic tutorial on javascript filter?

Filter of javascript? You can use css for simple filters and ps for high-end filters.
 

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.