[Java] JSP Notes-Filter filters

Source: Internet
Author: User
Tags response code tomcat server

First, what is a Web filter

Servlet APIs have long been a cornerstone of enterprise application development, while servlet filters are a relatively new complement to the Java EE family.

A Servlet filter is an pluggable Web component that allows us to implement preprocessing and post-processing logic in a Web application. Filters support the basic request processing capabilities of Servlets and JSP pages, such as logging, performance, security, session processing, XSLT transformations, and so on. The filter was originally published with the Java Servlet 2.3 specification.

What is a Servlet filter?
Servlet filters are small WEB components that intercept requests and responses to view, extract, or somehow manipulate data that is being exchanged between the client and server. Filters are WEB components that typically encapsulate some functionality, though important, but are not conclusive for processing client requests or sending responses. Typical examples include recording data about requests and responses, handling security protocols, managing session properties, and so on. Filters provide an object-oriented, modular mechanism for encapsulating common tasks into pluggable components that are declared by a configuration file and processed dynamically.

The Servlet filters combine a number of elements, making the filter a unique, powerful, and modular Web component. In other words, the Servlet filter is:

declarative : Filters are declared by using XML tags in the WEB deployment descriptor. This allows you to add and remove filters without having to change any application code or JSP pages.

Dynamic : The filter is called by the Servlet container at run time to intercept and process requests and responses.

Flexible : Filters are widely used in Web processing environments, covering many of the most common auxiliary tasks, such as logging and security. Filters are also flexible because they can be used to perform preprocessing and post-processing on direct calls from clients, and to handle requests that are dispatched between WEB components behind a firewall. Finally, you can link the filters to provide the necessary functionality.

Modular : By encapsulating application processing logic into a single class file, the filter defines a modular unit that can be easily added to or removed from the request/response chain.

Portable : Like many other aspects of the Java platform, Servlet filters are portable across platforms and containers, further supporting the modular and reusable nature of the Servler filter.

Reusable : Thanks to the modular design of the filter implementation class, and the declarative filter configuration, filters can be easily used across different projects and applications.

transparent : Include filters in the request/response chain, which is designed to complement (rather than in any way replace) the core processing provided by a servlet or JSP page. As a result, filters can be added or removed as needed without breaking the servlet or JSP pages.


So a Servlet filter is a modular reusable component that is flexibly declared through a configuration file. Filters dynamically process incoming requests and outgoing responses, and can add or remove them transparently without modifying the application code. Finally, filters are independent of any platform or Servlet container, allowing them to be easily deployed to any compatible Java EE environment.

Second, the first filter
 PackageCom.po;Importjava.io.IOException;ImportJavax.servlet.Filter;ImportJavax.servlet.FilterChain;ImportJavax.servlet.FilterConfig;Importjavax.servlet.ServletException;Importjavax.servlet.ServletRequest;ImportJavax.servlet.ServletResponse; Public classFirstfilterImplementsFilter {@Override Public voiddestroy () {System.out.println ("Destroy"); } @Override Public voidDoFilter (ServletRequest request, servletresponse response, Filterchain chain)throwsIOException, servletexception {System.out.println ("DoFilter:" +request.tostring ());            Chain.dofilter (request, response); } @Override Public voidInit (Filterconfig filterconfig)throwsservletexception {System.out.println ("Init:" +filterconfig.tostring ()); }}

Filters need to implement the filter interface:

init (): This method is called when the container instantiates a filter, and it is primarily designed to make the filter ready for processing. This method takes an object of type Filterconfig as input.

DoFilter (): As with the servlet having a service () method (which calls DoPost () or doget ()) to process the request, the filter has a single method--dofilter () for processing requests and responses. This method accepts three input parameters: a servletrequest, a response, and a Filterchain object.

Destroy (): As you can imagine, this method performs any cleanup operations that may need to occur before automatic garbage collection. Shows a very simple filter that tracks the approximate time it takes to satisfy a client's WEB request.

Third, configure Web. XML to enable filters

First look at this diagram:

Now, in Web. XML, we'll add these elements:

    <!--Filter Configuration -    <Filter>        <Filter-name>Firstfilter</Filter-name>        <Filter-class>Com.po.FirstFilter</Filter-class>    </Filter>    <filter-mapping>        <Filter-name>Firstfilter</Filter-name>        <Url-pattern>/*</Url-pattern>    </filter-mapping>

The filter tag is used to declare a filter, and each filter can have only one filter label.

The filter-mapping tag is used to specify the action object of the filter. In the example above, Url-pattern is set to "/*", which represents valid for all JSP requests.

After changing to Web. XML, the Tomcat server needs to be restarted.

When we restart the server, we can see that our filter init () was called in the console log.

To access a page in the browser, DoFilter will be executed.

Iv. Frequently Asked Questions

1. Can the filter change the Web resources requested by the user? That is, can you change the path of the user request?

Answer: Yes. For example, if the user is not logged in, a Web resource can be directed to the login page.

2. Can the filter directly return data, can you directly handle user requests?

Answer: No. Because the filter is not the same as the standard Servlet, it cannot return data directly. What if it points to a Web resource, or redirect to another Web resource.

Five or more filters

A Web service program can support multiple filters.

If a URL matches a URL specified by multiple filters, a filter chain is generated.

The server is assembled into a filter chain in the order defined by the filter in Web. Xml.

The execution process of the filter chain:

Vi. Classification of filters

The filter defaults to the Request type.

FORWARD Filter:

    <Filter>        <Filter-name>Firstfilter</Filter-name>        <Filter-class>Com.po.FirstFilter</Filter-class>            </Filter>    <filter-mapping>        <Filter-name>Firstfilter</Filter-name>        <Url-pattern>/index.jsp</Url-pattern>        <Dispatcher>FORWARD</Dispatcher>    </filter-mapping>

The include filter is similar to the FORWARD declaration, and the dispatcher is changed to include.

Error filter:

    <!--Error Filter -    <Error-page>        <Error-code>404</Error-code>        < Location>/error.jsp</ Location>    </Error-page>        <Filter>        <Filter-name>Errorfilter</Filter-name>        <Filter-class>Com.po.ErrorFilter</Filter-class>            </Filter>    <filter-mapping>        <Filter-name>Errorfilter</Filter-name>        <Url-pattern>/error.jsp</Url-pattern>        <Dispatcher>ERROR</Dispatcher>    </filter-mapping>

In versions of Servlet 3.0 and later, asynchronous support was added. It also adds the use of annotations to define filters (that is, we do not need to modify Web. xml).

Vii. @WebFilter Annotations Define Filters

Let's take a look at the common properties of @WebFilter.

Example: (Error filter)

 PackageCom.po;Importjava.io.IOException;ImportJavax.servlet.Filter;ImportJavax.servlet.FilterChain;Importjavax.servlet.ServletException;Importjavax.servlet.ServletRequest;ImportJavax.servlet.ServletResponse;Importjavax.servlet.annotation.WebFilter; @WebFilter (FilterName= "Errorfilter", Value={"/error.jsp"}, Dispatchertypes={Javax.servlet.DispatcherType.ERROR}) Public classErrorfilterImplementsFilter {@Override Public voidDoFilter (servletrequest request, servletresponse response, Filterchain chain)throwsIOException, servletexception {System.out.println ("DoFilter start.");        Chain.dofilter (request, response); System.out.println ("DoFilter end."); }}

The above code uses annotations to define the filter.

The following is an example of asynchronous filtering:

The first is to create a new servlet, which is used to handle complex asynchronous transactions.

 Packageservlet;Importjava.io.IOException;ImportJavax.servlet.AsyncContext;Importjavax.servlet.ServletException;ImportJavax.servlet.annotation.WebServlet;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;Importjavax.servlet.http.HttpServletResponse; @WebServlet (name= "Asyncservlet", asyncsupported=true, urlpatterns={"/servlet/asyncservlet"},description= "Asynchronous Filter Sample Servlet") Public classAsyncservletextendsHttpServlet {Private Static Final LongSerialversionuid = 1L; @Overrideprotected voidDoget (httpservletrequest req, HttpServletResponse resp)throwsservletexception, IOException {System.out.println ("Business request started."); Asynccontext Context=Req.startasync (); //To open an asynchronous thread        NewThread (NewExecutor (context)). Start ();
     Req.getrequestdispatcher ("/index.jsp"). Forward (req, resp);
//Resp.getwriter (). Close (); System.out.println ("Business request ended."); } Public classExecutorImplementsRunnable {PrivateAsynccontext context; PublicExecutor (Asynccontext context) { This. Context =context; } @Override Public voidrun () {Try { //Complex Business ProcessingSystem.out.println (Context.getrequest (). Getscheme ()); Thread.Sleep (10 * 1000); System.out.println ("Business execution is complete."); } Catch(interruptedexception e) {e.printstacktrace (); } } }}

Next, create an asynchronous filter.

 Packageservlet;Importjava.io.IOException;ImportJavax.servlet.Filter;ImportJavax.servlet.FilterChain;Importjavax.servlet.ServletException;Importjavax.servlet.ServletRequest;ImportJavax.servlet.ServletResponse;Importjavax.servlet.annotation.WebFilter; @WebFilter (FilterName= "Asyncfilter", Urlpatterns={"/servlet/asyncservlet"}, asyncsupported=true, Dispatchertypes={Javax.servlet.DispatcherType.ASYNC}) Public classAsyncfilterImplementsFilter {@Override Public voidDoFilter (servletrequest request, servletresponse response, Filterchain chain)throwsIOException, servletexception {chain.dofilter (request, response); }}

The characteristic of an asynchronous filter is that it can respond quickly to user requests, and complex business processes are executed in a new thread.

Of course, in our example code above, Asyncservlet.onget just starts a business processing thread and does not write the response code, so it causes a 500 error on the client. In real business, the output

[Java] JSP Notes-Filter filters

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.