Javaweb filter. Listener. Interceptor-? Principle & Difference

Source: Internet
Author: User

1, interceptors are based on the reflection mechanism of Java, filter is based on function callback
2. Interceptors are not dependent on the servlet container, and the filter relies on the servlet container
3. Interceptors can only work on action requests, and filters will work on almost all requests
4. The interceptor can access the action context, the object in the value stack, and the filter cannot
5, in the life cycle of the action, the interceptor can be called multiple times, and the filter can only be called once when the container is initialized

Interceptors: Is programming in the face of the plane is in your service or a method, before calling a method, or call a method after a method such as a dynamic proxy is a simple implementation of the Interceptor, before you call the method to print out the string (or other business logic operation), You can also print out a string after you invoke the method, even if you do business logic when you throw an exception.

The 1.struts2 interceptor is a method that accesses an action or action, the field is intercepted before or after it, and the Struts2 interceptor is pluggable and an interceptor is an implementation of AOP.
2. Interceptor Stack (interceptor stack). The Struts2 interceptor Stack is a chain that binds interceptors in a certain order. When accessing an intercepted method or field, interceptors in the Struts2 interceptor chain are invoked in the order in which they were previously defined.

Attached: 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 functions be dispersed into different objects, which is often referred to as assignment of responsibilities in software design. In fact, let's say that different classes are designed to have different methods. So the code is scattered in a class. The benefit of this is to reduce the complexity of the code and make the class reusable.

However, it is also found that the code duplication is increased while the code is dispersed. What do you mean? For example, in two classes, we may need to log in each method. In terms of object-oriented design, we have to include the contents of the log in the methods of two classes. Perhaps they are exactly the same, but it is because object-oriented design makes it impossible for a class to be associated with a class, but not to unify the duplicated code.
Someone might 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 with the independent classes we mentioned above, and the changes will affect these two classes. So, is there any way that we can randomly add code when we need it? At run time, the programming idea of dynamically cutting code into the class, at the specified location, is the aspect-oriented programming.
In general, the code snippet in which we cut into the specified class is called a slice, and which class to cut into and which method is called the pointcut. With AOP, we can extract several classes of common code into a slice, and then cut into the object when needed, thus altering its original behavior.
In this way, AOP is really just a complement to OOP. OOP distinguishes a class from a landscape, while AOP adds a specific code to the object vertically. With the Aop,oop became three-dimensional. If you add a time dimension, AOP makes OOP from the original two dimensions into three-dimensional, from the plane to three-dimensional. Technically, AOP is basically implemented through proxy mechanisms.
AOP can be a milestone in programming history, and it is a useful complement to OOP programming.


The following example looks at the difference between filters and interceptors:

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
     } 

filters: In the Java Web, your incoming request,response filters out some of the information ahead of time, or sets some parameters ahead of time, and then passes in the servlet or struts action for business logic. For example, filter out illegal URLs (not login.do address requests, if the user does not log on to filter out), or in the servlet or struts before the action of the uniform set of character sets, or to remove some illegal characters. Mainly in order to reduce the server load, reduce pressure.

using filters to filter the 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 is a filtered implementation class:
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 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 arg0) throws Servletexception {

     } 
}

Javaweb filter. Listener. Interceptor-? Principle & Difference

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.