Javaweb Filter-operating mechanism understanding and filters-listeners-interceptors-principles & differences

Source: Internet
Author: User
Tags aop auth character set java web

Filters Filter Filter


I. The concept of a filter.


Filter, also known as filters, is the most useful technology in Servlet technology, Web developers through the filter technology, Web server management of all Web resources: such as JSP, Servlet, static picture files or static HTML files to intercept, In order to realize some special functions. such as the implementation of URL-level access control, filtering sensitive words, compressed response information, and other advanced features.

Two. The operation mechanism of the filter.


The Web project running mechanism without filter is as follows:

Add filter to the web operation mechanism:

This shows: The role of filter is green website, protect the website, realize the control of access rights and so on.


Three. How to achieve a filter.

Write a class to implement the filter interface.

Configure Filter

<!--  Configuration filter  --> <filter>   <!--  Filter name  -->   <filter-name>FilterDemo1</filter-name>   <!--  Filter class full path  -->   <filter-class>cn.itcast.filter.FilterDemo1</filter-class> </ Filter>   <!--  Configuration filter Mappings  --> <filter-mapping>   <!--  Filter Name  --
>   <filter-name>FilterDemo1</filter-name>   <!--  Filter Path  -->   <url-pattern>/*</url-pattern> </filter-mapping> 

The



<filter-name> is used to specify a name for the filter, and the contents of the element cannot be empty. The
<filter-class> element is used to specify the complete qualified class name for the filter. The

   <init-param> element is used to specify the initialization parameter for the filter, its child element <param-name> the name of the specified parameter,<param-value> the value of the specified parameter. In a filter, you can use the Filterconfig interface object to access the configuration of the initialization parameter

<url-pattern> label:

* Full path matching: To/start./aa /bb/aa/bb ...

* Directory matching    : To/start. to * end. such as/*/aa/*/aa/bb/*

* Extension match  : cannot start with/. If *.jsp&nbs P After the filter is configured by the *.do  *.action

, the filter path that matches its own path is automatically searched before the server invokes the servlet, and the filter is executed after the match. No match, the servlet is called directly.

Four. The concept of a filter chain.

Typically after a client requests a server, a set of filters (multiple filters) is executed before the server invokes the servlet, and the set of filters is called a filter chain.

   Each filter implements a specific feature, and a filter detects multiple servlet. (Match several, detect several). The order of execution in a set of filters in

is related to the order in which the <filter-mapping> is configured.

When the Dofilter method of the first filter is invoked, the Web server creates a Filterchain object that represents the filter chain to pass to the 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 any filter in the Filterchain object, and if so, calls the 2nd filter, if not, The target resource is invoked.


Five. The life cycle of the filter.
  
Life cycle diagram:

  
Three ways:
  
Linit (Filterconfig filterconfig) throws Servletexception:
Like the servlet program we write, the Web server is responsible for the creation and destruction of the filter. When the Web application starts, the Web server creates an instance object of the filter and invokes its Init method for initialization (note: The filter object is created only once and the Init side executes only once).
The developer uses the parameters of the Init method to obtain the Filterconfig object that represents the current filter configuration information. (Filterconfig object see next page ppt) Ldofilter (servletrequest,servletresponse,filterchain) Every time the filter is intercepted, the parameter request and response are usually converted to HttpServletRequest and HttpServletResponse types for operation in the actual development method.
  
Dofilter (Servletrequest,servletresponse,filterchain):
Every time the filter is intercepted, it executes.
In practical development, parameter request and response are usually converted to HttpServletRequest and httpservletresponse types for operation.

Destroy ():
Called before the Web container unloads the Filter object.


Six. The operation mechanism of the filter chain.

 
Analysis Operation Mechanism:

The Dofilter in the filter is the Dofilter (Request,response) method of the filter instance.

This chain of responsibility is run in sequence: Code 1, Code 3, code 5,servelt, Web Resources ..., code 6, code 4, code 2; it's because of its end-to-end mechanism, so it's called the chain of responsibility.

In filter, if you do not call the Chain.dofilter (Request,response) method, it means that the request was rejected and returned to the target path.

Seven. Get configuration information for the filter in the Web.xml file.

The calling object for the method:

The FILTERCONIFG object in the init (Filterconfig filterconfig) method.

Method:

Getfiltername (): Get Filter Name

Getinitparameter (String name): Gets the initialization parameters for the filter

Getinitparameternames (): Gets the name of all initialization parameters for the filter

Getservletcontext (): Get ServletContext Object




Javaweb Filters-Listeners-interceptors-principles & differences


1, the Interceptor is based on the Java reflection mechanism, and the filter is based on function callback

2, the filter depends on the servlet container, and the interceptor does not depend on the servlet container

3, the interceptor can only work on the action request, and the filter can work on almost all requests

4, the interceptor can access the action context, value stack objects, and filters can not

5. In the life cycle of the action, the interceptor can be invoked multiple times, and the filter can only be invoked once when the container is initialized



Intercepting device:Is programming on the face of the plane is in your service or a method, calling a method before, or calling a method after a method such as a dynamic proxy is a simple implementation of the Interceptor, printing out a string (or doing other business logic) before you invoke the method, or printing out a string after you call the method, Do business logic even when you throw out an exception.


The 1.struts2 interceptor is an implementation of AOP by accessing a method of an action or action, blocking it before or after the field, and the Struts2 interceptor is pluggable.

2. Interceptor Stack (interceptor stack). The Struts2 interceptor Stack is a chain that connects the interceptor in a certain order. When accessing a blocked method or field, the interceptor in the Struts2 interceptor chain is invoked in the order in which it was previously defined.


Attach: Aspect-oriented programming (AOP is the acronym for Aspect Oriented program), we know that object-oriented features are inheritance, polymorphism, and encapsulation. Encapsulation requires that the function be dispersed to different objects, which is often called responsibility assignment in software design. In other words, let the different classes design different methods. So the code is dispersed into a class. The benefit of this is to reduce the complexity of the code and make the class reusable.
But it has also been found that the code is more repetitive as it is distributed. What does that mean? For example, in two classes, we might need to log in each method. In the object-oriented design approach, we have to include the contents of the log in the two-class approach. Maybe they are exactly the same, but because object-oriented design makes it impossible to connect classes to classes, and not to unify these repetitive code.

Maybe someone would say, well, we can write this code in a separate class-independent method, and then call it in these two classes. However, in this way, these two classes are coupled to the independent classes we mentioned above, and their changes affect these two classes. So, is there any way that we can randomly add code when we need it? At runtime, the programming idea of dynamically slicing code into the specified method of the class, specifying the location, is the aspect-oriented programming.

In general, the code fragment that we cut into the specified method of the specified class is called the slice, and which classes and which methods are called pointcuts. With AOP, we can extract code that is common to several classes into a slice, and then move on to the object as needed to change its original behavior.

In this way, AOP is just a complement to OOP. OOP distinguishes a class from the landscape, while AOP adds a specific code to the object vertically. With the Aop,oop become stereo. If you add the time dimension, AOP makes oop from the original two-dimensional to three-dimensional, from the plane into three-dimensional. Technically, AOP is basically implemented through proxy mechanisms.

AOP is a landmark in the history of programming and is a useful complement to OOP programming.

Here's an example to see the difference between a filter and a interceptor:

Using interceptors to filter JSP pages in the/admin directory

<package name= "Newsdemo"  extends= "Struts-default"          
 namespace= "/admin" >          <interceptors>              <interceptor name= "Auth"   class= "Com.test.news.util.AccessInterceptor"  />               <interceptor-stack name= "Authstack" >                   <interceptor-ref name= "Auth"  / >              </interceptor-stack>           </interceptors>           <!-- action -->           <action Name= "newsadminview!*"  class= "newsaction"                method= ' {1} ' >               <interceptor-ref name= "Defaultstack"/>               <interceptor-ref name= "Authstack" >               </interceptor-ref>


Here is the Interceptor Class I implemented:


package com.test.news.util;  import java.util.map;  import  com.opensymphony.xwork2.actioncontext;  import com.opensymphony.xwork2.actioninvocation;  Import  com.opensymphony.xwork2.interceptor.AbstractInterceptor;  import  com.test.news.action.adminloginaction; /**  *  @author  chaoyin */    Public  class AccessInterceptor extends AbstractInterceptor {       
 private static final long serialVersionUID = -4291195782860785705L;       @Override       public string intercept ( actioninvocation actioninvocation)  throws Exception {            actioncontext actioncontext = actioninvocation.getinvocationcontext ();            map sessioN = actioncontext.getsession ();                   //except login action            object action = actioninvocation.getaction ();           if  (action instanceof adminloginaction)  {               return actioninvocation.invoke ();            }          //check  session          if (Session.get ("user") ==null ) {               return  "Logout";            }          return  ActioninvocatiOn.invoke ();//go on       } } 


Filter: is in the Java Web, your incoming request,response filter out some information in advance, or set some parameters in advance, and then pass in the servlet or struts Action carries out business logic, such as filtering out illegal URLs (not login.do address requests, if the user is not logged in), or setting the character set uniformly before passing in a servlet or struts action, or removing some illegal characters. Mainly to reduce server load, reducing pressure.


Use filters to filter JSP pages in the/admin directory, first filter configuration in Web.xml:

<filter>
<filter-name>access filter</filter-name>
<filter-class>
Com.test.news.util.AccessFilter
</filter-class>
</filter>
<filter -mapping>
<filter-name>access filter</filter-name>
<url-pattern>/admin/*< ;/url-pattern>
</filter-mapping>



The following are the implementation classes for filtering:

package com.test.news.util;  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.http.httpservletrequest;  import  javax.servlet.http.httpservletresponse;  import javax.servlet.http.httpsession;  public  class accessfilter implements filter { /**  *  @author  chaoyin  *           public void destroy ()  {          }      public void dofilter (servletrequest arg0 , servletresponse arg1,                filterchain&nbSp;filterchain)  throws IOException, ServletException {            HttpServletRequest request =  (httpservletrequest) arg0;            HttpServletResponse response =  ( HttpServletResponse) arg1;           httpsession session  = request.getsession ();          if ( Session.getattribute ("User") == null && request.getrequesturi (). IndexOf ("login.jsp") ==-1  ) {                Response.sendredirect ("login.jsp");               return ;           }            filterchain.dofilter (Arg0, aRG1);         }      public void init ( FILTERCONFIG&NBSP;ARG0)  throws ServletException {         }  }


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.