Java Web advanced -- Filter filter, advanced Filter

Source: Internet
Author: User

Java Web advanced -- Filter filter, advanced Filter

Blog: http://wxmimperio.coding.io/

My mailbox: wxmimperio@163.com

 

1. Introduction to filters:
  • A filter is defined in Servlet specification 2.3. It is a server component that can intercept user-side request and Response Information and filter the information.
  • The Servlet filter does not generate request and response objects, but provides the filter function.
  • The Servlet filter can check the Request object before the Servlet is called and modify the Request Header and Request content.
  • Web components that can be filtered by Servlet filters include Servlet, JSP, HTML, and other files.

Source code -- GitHub:

Https://github.com/imperio-wxm/wordpressCode/tree/master/Filter

II. Application scenarios of filters in actual development 1. perform unified authentication for user requests. encoding conversion 3. filter and replace user-sent data. 4. convert image formats 5. compress corresponding content Iii. How filters work

[No filter ]:

You can directly access WEB resources.

[With filter ]:

When the WEB Container starts, it loads the filter. The user sends a request to the filter, and the filter determines whether the request meets the rules. Requests that comply with the rules are sent to WEB resources through the filter, the WEB Resource response information is returned to the filter, and the filter then returns the WEB resource response to the user.

4. lifecycle of the filter (similar to the Servlet lifecycle)

1. instantiation-configuration loading through web. xml, Which is instantiated only once at container startup
2. initialize -- call the init () method and load the information only once.
3. filter -- use the doFilter () method to filter multiple times
4. destroy -- call the destroy () method to destroy the WEB Container when it is disabled.

All Servlet filters must implement the javax. servlet. Filter interface and implement the three methods in this interface.

[Init () method]
  • This is the initialization method of the filter. This method will be called after the web Container creates a filter instance. This method can be used to filter parameters in the web. xml file.
[DoFilter () method]
  • This method completes the actual filtering operation. This is the core method of the filter. When a user requests to access the URL associated with the filter, the web Container will first call the doFilter method of the filter.
  • FilterChain method parameters can call the chain. doFilter method to send requests to the next filter (or target resource), or forward requests to other resources by means of forwarding or redirection.
[Destroy () method]
  • The web Container calls this method before destroying the filter instance. In this method, the resources occupied by the filter can be released.

[Life Cycle Code demo]

 

package com.filter;import javax.servlet.*;import java.io.IOException;/** * Created by wxm-Imperio */public class FirstFilter implements Filter {   @Override   public void destroy() {      System.out.println("destroy,firstFilter");   }   @Override   public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) 
      throws IOException, ServletException { System.out.println("start,doFilter,firstFilter"); filterChain.doFilter(servletRequest, servletResponse); System.out.println("End,doFilter,firstFilter"); } @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("init。firstFilter"); }}

Web. xml configuration]

<Filter> <filter-name> Filter name </filter-name> <filter-class> name of the Filter class </filter-class> <init-param> <description> the description can be omitted or placed here </description> <param-name> parameter name </param-name> <param-value> parameter value </param-value>/ init-param> </filter> <filter-mapping> <filter-name> Filter name </filter-name> <url-pattern> URL </url-pattern> <dispatcher> </dispatcher> // filter type </filter-mapping>

Note: Generally, filters are configured before all servlets.

5. Support for multiple Filters
  • Each filter has a different URL address.
  • When different filter URLs are the same, a filter chain is generated:
  • User requests-in turn, each filter-web resources (the order is: the server forms a chain according to the order defined by the filter in web. xml)
[User request] --> [filter 1Chain. doFilter code --> filter 1Chain. doFilter --> filter 2Chain. doFilter code --> filter 1Chain. doFilter .......] --> [Servlet Service Method Processing request] --> ........... [filter 2Chain. doFilter code --> filter 1Chain. doFilter Code] --> [return user request]

[Web. xml configuration of the filter chain]

<! -- Configuration information of filter 1 --!> <Filter> <filter-name> Filter1 name </filter-name> <filter-class> Filter1 class name </filter-class> <init-param> <description> the description can be omitted or placed here </description> <param-name> parameter name </param-name> <param-value> parameter value </param-value>/ init-param> </filter> <filter-mapping> <filter-name> Filter1 name </filter-name> <url-pattern> URL </url-pattern> <dispatcher> </dispatcher> // filter type </filter-mapping> <! -- Configuration information of filter 2 --!> <Filter> <filter-name> Filter2 name </filter-name> <filter-class> Filter2 class name </filter-class> <init-param> <description> the description can be omitted or placed here </description> <param-name> parameter name </param-name> <param-value> parameter value </param-value>/ init-param> </filter> <filter-mapping> <filter-name> Filter2 name </filter-name> <url-pattern> URL </url-pattern> <dispatcher> </dispatcher> // filter type </filter-mapping>

Note: The execution sequence of the filter is configured in web. xml.

6. Filter Classification

Servlet2.5:

1. When the REQUEST (default) user directly accesses the page, the web Container will call the filter. 2. When the target FORWORD source is accessed through the forword method of RequestDispatcher, this filter is called. 3. When the target resource is called through the INCLUDE method of RequestDispatcher, the filter is called. 4. When the ERROR target resource is called through the declarative Exception Handling Mechanism, the filter will be called. [Syntax]
@ WebFilter (servletNames = {"SimpleServlet"} filterName = "SimpleFilter") public class LessThanSixFilter implements Filter {// content in the class}

[ERROR configuration information]

<error-page>   <error-code>404</error-code>   <location>/error.jsp</location></error-page><filter>   <filter-name>errorFilter</filter-name>   <filter-class>com.filter.ErrorFilter</filter-class></filter><filter-mapping>   <filter-name>errorFilter</filter-name>   <url-pattern>/error.jsp</url-pattern></filter-mapping>

[ErrorFilter filter code]

Public class implements Filter {@ Override public void destroy () {}@ Override public void init (FilterConfig filterConfig) throws ServletException {}@ Override public void doFilter (ServletRequest servletRequest, too many, filterChain filterChain)
Throws IOException, ServletException {System. out. println ("error message detected ");}}

 

Servlet3.0:

(New) ASYNC supports asynchronous Processing
  • @ WebFilter (Introduction) is used to declare a filter. The annotation will be processed by the container during deployment, and the container will configure the corresponding class as the filter according to the specific attributes.

[Asynchronous Operation Processing code: the filter directly executes the following content without waiting for the thread to Implement Asynchronous processing]

AsynServlet

// Set Servlet support asynchronous @ WebServlet (name = "AsynServlet", asyncSupported = true) public class AsynServlet extends HttpServlet {protected void doPost (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, IOException {System. out. println ("Servlet execution start time" + new Date (); // implement AsyncContext context = request. startAsync (); // enable the asynchronous Thread new Thread (new Executor (context )). start (); System. out. println ("Servlet execution End Time" + new Date ();} protected void doGet (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, IOException {doPost (request, response);} // internal class simulation thread public class Executor implements Runnable {private AsyncContext context; // implements the constructor public Executor (AsyncContext context) {this. context = context ;}@ Override public void run () {// execute related complex business try {Thread. sleep (1000*10); // context. getRequest (); // context. getResponse (); System. out. println ("business execution completion time" + new Date ();} catch (InterruptedException e) {e. printStackTrace ();}}}}

 

AsvnFilter

// Annotation @ WebFilter (filterName =
"AsynFilter", value = {"/AsynServlet"}, asyncSupported = true, dispatcherTypes = {DispatcherType. REQUEST, DispatcherType. ASYNC}) public class AsynFilter implements Filter {@ Override public void destroy () {}@ Override public void init (FilterConfig filterConfig) throws writable {}@ Override public void doFilter (ServletRequest servletRequest, servletResponse servletResponse, FilterChain)
Throws IOException, ServletException {System. out. println ("Start .......... asynFilter "); filterChain. doFilter (servletRequest, servletResponse); System. out. println ("End .......... asynFilter ");}}

Web. xml configuration

<servlet>   <servlet-name>AsynServlet</servlet-name>   <servlet-class>com.servlet.AsynServlet</servlet-class></servlet><servlet-mapping>   <servlet-name>AsynServlet</servlet-name>   <url-pattern>/AsynServlet</url-pattern></servlet-mapping>
VII. Use of FilterConfig

The init method of Filter provides a FilterConfig object and related operations:

For example, to obtain the initialization parameter web. xml configuration configured in the Filter:

<filter>      <filter-name>LoginFilter</filter-name>      <filter-class>com.itzhai.login.LoginFilter</filter-class>      <init-param>          <param-name>username</param-name>          <param-value>arthinking</param-value>      </init-param></filter>

Obtain the following information in the init () method:

@ Overridepublic void init (FilterConfig filterConfig) throws ServletException {// get the Filter initialization parameter String username = filterConfig. getInitParameter ("username ");}

Access application in Filter:

ServletContext context = filterConfig.getServletContext();

You can also get the result according to the converted request in the doFilter method:

HttpServletRequest req = (HttpServletRequest)request;ServletContext context = req.getSession().getServletContext();
8. Project instances

The enhanced version of the Demo for user logon in MOOC, which uses filters to filter requests and server responses.

GitHub Source: https://github.com/imperio-wxm/projectDemo

For details, refer to: JSP Application Development (the third edition) and MOOC.

 

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.