Java Interceptor (Interceptor) Learning notes

Source: Internet
Author: User
Tags aop

1, the concept of interceptors
The Interceptor in Java is the object that dynamically intercepts action calls, and it provides a mechanism to enable a developer to execute a piece of code before and after an action execution, or in an action
Prevents execution before execution, and also provides a way to extract reusable portions of the code in the action. In AOP, interceptors are used to intercept a method or field before it is accessed
Then add some actions before or after. At present, we need to master the main spring interceptors, Struts2 interceptors do not have to delve into, know.

Filter, Listener, Interceptor diff diagram

2, the principle of the Interceptor
Most of the time, the Interceptor method is invoked in the form of proxies. Struts2 interceptors are relatively simple to implement. When the request arrives at Struts2 's Servletdispatcher, Struts2
Finds the configuration file and instantiates the Interceptor object relative to the configuration, and then strings it into a list, the last one of the interceptors in the call list. Struts2 interceptors are available
Pluggable, interceptors are an implementation of AOP. The Struts2 interceptor Stack is a chain in which the interceptors are connected in a certain order. When accessing intercepted methods or fields, the STRUTS2 interceptor chain
will be invoked in the order in which they were previously defined.

3. Steps to customize the Interceptor
The first step: Customizing a class that implements the Interceptor interface, or inheriting the abstract class Abstractinterceptor.
Step Two: Register the defined interceptor in the configuration file.
The third step: in the need to use the action to reference the above-defined interceptor, in order to facilitate the interceptor can also be defined as the default interceptor, so that without special instructions, all
The action is intercepted by this interceptor.

4, the difference between the filter and the Interceptor
Filters can simply be understood as "take what you Want", the filter is concerned about the Web request, the interceptor can be simply understood as "reject you want to refuse", the interceptor is concerned about the method call, such as interception
Sensitive vocabulary.
4.1, interceptors are implemented based on the Java reflection mechanism, and filters are implemented based on function callbacks. (Some say interceptors are implemented based on dynamic proxies)
4.2, the interceptor does not rely on the servlet container, and the filter relies on the servlet container.
4.3, the Interceptor only works on the action, and the filter can work on all requests.
4.4, the interceptor can access the action context and the object in the value stack, and the filter cannot.
4.5, the interceptor can be called multiple times during the life cycle of the action, and the filter can only be called once when the container is initialized.

5,spring Interceptor
5.1, abstract class Handlerinterceptoradapter
If we use the Spring framework in our project, we can directly inherit the abstract class of Handlerinterceptoradapter.java to implement our own interceptors.

The spring framework, which wraps the concept of the Interceptor in Java, is similar to the Struts2. Handlerinterceptoradapter inherits the abstract interface Handlerinterceptor.

Look at the source code:

 PackageOrg.springframework.web.servlet.handler; Importjavax.servlet.http.HttpServletRequest; ImportJavax.servlet.http.HttpServletResponse; ImportOrg.springframework.web.servlet.HandlerInterceptor; ImportOrg.springframework.web.servlet.ModelAndView;  Public Abstract classHandlerinterceptoradapterImplementshandlerinterceptor{//called before the business processor processes the request     Public BooleanPrehandle (HttpServletRequest request, httpservletresponse response, Object handler)throwsexception{return true; }      //after the business processor finishes processing the request, the view executes before it is generated     Public voidPosthandle (httpservletrequest request, httpservletresponse response, Object handler, Modelandview Modelandview) throwsexception{}//called after Dispatcherservlet completely finishes processing the request and can be used to clean up resources     Public voidaftercompletion (httpservletrequest request, httpservletresponse response, Object handler, Exception ex)throwsexception{}}

Below, we use the handlerinterceptoradapter provided by the spring framework to pump out classes to implement a custom interceptor. We have this interceptor called
Userlogininterceptor, perform login interception control. The workflow is this: if the current user is not logged in, then jump to the login page, after the successful login, continue to access.

 PackageCom.singlee.capital.approve.service;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;ImportOrg.springframework.web.servlet.ModelAndView;ImportOrg.springframework.web.servlet.handler.HandlerInterceptorAdapter; Public classUserlogininterceptorextendsHandlerinterceptoradapter {//called before the business processor processes the request     Public BooleanPrehandle (HttpServletRequest request, httpservletresponse response, Object handler)throwsexception{String RequestUri=Request.getrequesturi (); String ContextPath=Request.getcontextpath (); String URL=requesturi.substring (Contextpath.length ()); System.out.println ("RequestUri" +RequestUri); System.out.println ("ContextPath" +ContextPath); System.out.println ("url" +URL); String username= (String) request.getsession (). getattribute ("username"); //determine if there are login user information in session        if(NULL==username) {              //Jump to login pageRequest.getrequestdispatcher ("/web-inf/login.jsp"). Forward (request, response); return false; }          Else{              return true; }    }      //after the business processor finishes processing the request, the view executes before it is generated     Public voidPosthandle (httpservletrequest request, httpservletresponse response, Object handler, Modelandview Modelandview) throwsexception{}//called after Dispatcherservlet completely finishes processing the request and can be used to clean up resources     Public voidaftercompletion (httpservletrequest request, httpservletresponse response, Object handler, Exception ex)throwsexception{}}

Summarize:
1. Filter: The so-called filter, as the name implies is used to filter, Java Filter can provide us with system-level filtering, that is, to filter all Web requests,
This is something that the interceptor cannot do. In the Java Web, your incoming request,response filters out some of the information ahead of time, or sets some parameters in advance before passing in the servlet or
The action of the struts, such as filtering out illegal URLs (not login.do address requests, if the user is not logged in and filtering out), or in the incoming servlet or struts
Action, or remove some illegal characters (often used in chat rooms, some curse words). The filter process is linear, and after the URL has been checked,
You can keep the original process going down and be received by the next filter, the servlet.
2. Listener (Listener): Java Listener, is also the system level of monitoring. The listener starts with the launch of the Web App. Java listener is often used in C/s mode, it
Generates a process for a particular event. Monitoring is used in many modes, such as observer patterns, which are implemented using listeners, such as counting the number of online people on a website.
Another example is that STRUTS2 can be started with monitoring. The servlet listener is used to listen for important events, and the listener object can do the necessary work before and after it occurs.
3. Interceptor (Interceptor): The Interceptor in Java provides non-system level interception, that is, in terms of coverage, interceptors are not as powerful as filters, but more targeted.
The Interceptor in Java is implemented based on the Java reflection mechanism, and the more accurate partition should be the dynamic agent based on the JDK implementation. It relies on a specific interface to dynamically generate bytecode during run time.
Interceptors are objects that dynamically intercept action calls, and provide a mechanism to enable a developer to execute a piece of code before and after an action executes, or to block a action before it executes
execution, but also provides a way to extract reusable portions of the code in an action. In AOP, interceptors are used to intercept a method or field before it is accessed, before or
To add some actions after the user.

The next note is the detailed difference between the interceptor and the filter

Java Interceptor (Interceptor) Learning notes

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.