Java Web Learning: Filter Learning (i)

Source: Internet
Author: User
Tags java web

What is a filter

Filter scenes in your life:

What is a Web filter

The Web filter filters user requests, but does not process the results.

Filters include: Filter source, filter rules and filter results.

The concept of filters

A filter is a server-side component that intercepts the client's request and response information and filters the information.

How the filter works

Assuming that we are accessing Web resources:

1) without filter:

2) in the case of a filter:

How the Filter works:

Filters intercept requests and responses to view, extract, or somehow manipulate data that is being exchanged between the client and server.

Filters can only be server-side jumps for user requests, not directly returning data because the filter is not a standard servlet page.

The filter is defined in Java servlet Specification 2.3 and is capable of inspecting and modifying the request and response objects of the servlet container.  

The filter itself does not produce a request and response object, it can only provide filtering effect. The filter is able to check the request before the servlet is invoked

object, modify the request header and request content, examine the response object after the servlet is invoked, modify the response header and

Response content.

The Web component that the filter is responsible for filtering can be a servlet, JSP, or HTML file.

The role of the filter

1 filters are executed in front of a set of resources;

2 filters allow the request to get the target resource, or not to allow the request to reach;

3 filters have the ability to intercept requests

life cycle of filters

The life cycle of a filter consists of:

Instantiate--web.xml or annotations

Initialize--init ()

Filter--dofilter ()

Destroy--destroy ()

The three important methods of filter are:

Init () method

The init () method is the initialization method of the filter, which is called when the Web container creates the filter instance, which can be read in the XML text

Parameters of the filter in the piece.

DoFilter () method

The DoFilter () method completes the actual filtering operation, the local hair is the core method of the filter, when the user requests to access the URL associated with the filter,

The Web container will first call the filter's Dofilter () method. The Filterchain parameter can call the Chain.dofilter () method to pass the request to the next filter

(or target resource), or by forwarding, redirecting requests to other resources.

Destroy () method

The Destroy () method is called by the Web container before destroying the filter instance, in which the resource used by the filter can be freed, in most cases

Less than.

about the Web. XML Configuration

Can filters change the Web resources requested by the user? That is, can you change the path of the user request? OK

Can the filter directly return data, can it directly handle user requests? No

making the first filter using annotations

How the filter is written:

1 Write a class implementation filter interface

2 Configure or use annotations in Web. Xml.

Code implementation

Firstfilter.java Source code:

Package Com.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 javax.servlet.annotation.webfilter;/** * servlet Filter Implementation class Firstfilter */@WebFilter (filtername= "Firstfilter", urlpatterns={"/index.jsp"}) public class Firstfilter implements      Filter {/** * Default constructor. */Public Firstfilter () {//TODO auto-generated constructor stub}/*** @see Filter#destroy ()*/public void Destroy () {TODO auto-generated Method StubSYSTEM.OUT.PRINTLN ("Destroy------firstfilter");}/*** @see Filter#dofilter (servletrequest, Servletresponse, Filterchain)*/public void DoFilter (ServletRequest request, servletresponse response, Filterchain chain) throws IOException, servletexception {TODO auto-generated Method StubPlace your code hereSystem.out.println ("Start------firstfilter");Pass the request along the filter chainChain.dofilter (request, response);SYSTEM.OUT.PRINTLN ("End------firstfilter");}/*** @see Filter#init (filterconfig)*/public void init (Filterconfig fconfig) throws Servletexception {TODO auto-generated Method StubSYSTEM.OUT.PRINTLN ("init------firstfilter");}}

Index.jsp page Code:

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >

Operation Result:

The Destroy () method is destroyed before the server shuts down.

filter Chain

Web projects support multiple filters.

Filterchain.dofilter () method

The method is to execute the target resource, or execute the next filter, if there is no next filter, then execute the target resource, if there is,

Then execute the next filter.

Order of execution for multiple filters:

The <filter-mapping> configuration order of the Web. XML configuration file determines the order in which the filters are executed.

The order in the annotations is difficult to control, and the order of the initials is noted when the filter is named, which is generally the basis for the order of execution.

filter Chain

Filter:

Execution process:

Code implementation

On the basis of the first filter we add a second filter to filter the same page.

Secondfilter.java Source code:

Package Com.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 javax.servlet.annotation.webfilter;/** * servlet Filter Implementation class Secondfilter */@WebFilter (filtername= "Secondfilter", urlpatterns={"/index.jsp"}) public class Secondfilter      Implements Filter {/** * Default constructor. */Public Secondfilter () {//TODO auto-generated constructor stub}/*** @see Filter#destroy ()*/public void Destroy () {TODO auto-generated Method StubSYSTEM.OUT.PRINTLN ("Destroy------secondfilter");}/*** @see Filter#dofilter (servletrequest, Servletresponse, Filterchain)*/public void DoFilter (ServletRequest request, servletresponse response, Filterchain chain) throws IOException, servletexception {TODO auto-generated Method StubPlace your code hereSystem.out.println ("Start------secondfilter");Pass the request along the filter chainChain.dofilter (request, response);SYSTEM.OUT.PRINTLN ("End------secondfilter");}/*** @see Filter#init (filterconfig)*/public void init (Filterconfig fconfig) throws Servletexception {TODO auto-generated Method StubSYSTEM.OUT.PRINTLN ("init------secondfilter");}}

Execution Result:

The Destroy method is also executed before shutting down the server.







Java Web Learning: Filter Learning (i)

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.