Detailed explanation of the principle and application of Java Web interceptor

This article mainly introduces the principle and application details of the Java Web interceptor, which is introduced in great detail through the example code. It has a certain reference value for everyone's study or work. Friends in need can refer to it

1、 Introduction

Interceptors in Java provide non system level interception, that is, in terms of coverage, interceptors are not as powerful as filters, but they are more targeted.

Interceptors in Java are implemented based on java reflection mechanism. For more accurate division, they should be dynamic agents based on JDK. It depends on the specific interface and dynamically generates bytecode during operation.

Interceptor is an object that dynamically intercepts action calls. It provides a mechanism to enable developers to execute a piece of code before and after the execution of an action, or to prevent the execution of an action before it is executed. At the same time, it also provides a way to extract reusable code in an action. In AOP, interceptors are used to intercept a method or field before it is accessed, and then add some operations before or after it. Java interceptors are mainly used in plug-ins and extensions, such as hibernate spring struts 2, which are somewhat similar to slicing oriented technology. Before using them, you must declare a paragraph in the configuration file, that is, XML.

The interceptor interceptor in spring MVC is mainly used to intercept the user's URL request and add some special requests before, during and after executing the handler method, which is similar to the filter in the servlet

Interceptor interceptor in spring MVC is also very important and useful. Its main function is to intercept user requests and process them accordingly. For example, it can be used for permission verification, or to judge whether the user logs in, or whether the current time is the ticket purchase time like 12306.

2、 Application scenario

1. Log recording can record the log of request information for information monitoring, information statistics, etc.

2. Permission check: for example, for login detection, enter the processor to detect whether to log in. If not, return to the login page directly.

3. Performance monitoring: typically slow logs.

3、 Realize

3.1 implementation mode

Interceptor in spring MVC intercepts requests through handlerinterceptor. Defining an interceptor in spring MVC is very simple. There are two main ways,

Mode 1:

The interceptor class defined should implement the handlerinterceptor interface of spring, or this class inherits the class that implements the handlerinterceptor interface, such as the abstract class handlerinterceptoradapter that implements the handlerinterceptor interface provided by spring;

Mode 2:

Implement the webrequestinterceptor interface of spring, or inherit the class that implements webrequestinterceptor.

Detailed description of implementing handlerinterceptor interface:

Three methods are defined in the handlerinterceptor interface. We use these three methods to intercept user requests.

(1) Prehandle (HttpServletRequest request, httpservletresponse, object handle) method. As the name suggests, this method will be called before request processing. Interceptors in spring MVC are called in a chain. Multiple interceptors can exist simultaneously in an application or in a request. Each interceptor call will be executed in sequence according to its declaration order, and the first execution is the prehandle method in the interceptor. Therefore, some pre initialization operations or preprocessing of the current request can be carried out in this method, or some judgments can be made in this method to determine whether the request should continue. The return value of this method is of boolean type. When it returns false, it means that the request ends and subsequent interceptors and controllers will not execute again; When the return value is true, it will continue to call the prehandle method of the next interceptor. If it is the last interceptor, it will call the controller method of the current request.

(2) The posthandle (HttpServletRequest request, object handle, modelandview, modelandview) method is explained by the prehandle method. We know that this method, including the aftercompletion method to be mentioned later, can only be called when the return value of the prehandle method of the current interceptor is true. As the name suggests, the posthandle method is executed after the current request is processed, that is, after the controller method is called, but it will be called before the dispatcher servlet renders the view return, so we can operate the modelandview object after the controller processing in this method. The posthandle method is called in the opposite direction to the prehandle, that is, the posthandle method of the interceptor declared first will be executed later, which is somewhat different from the execution process of the interceptor in struts 2. The execution process of the interceptor in struts 2 is also chained, but in struts 2, you need to manually call the invoke method of actioninvocation to trigger the call to the next interceptor or or action. Then, the contents before the invoke method call in each interceptor are executed in the declared order, and the contents after the invoke method are reversed.

(3) Aftercompletion (HttpServletRequest request, exception Ex) method, which is also executed only when the return value of the prehandle method of the current corresponding interceptor is true. As the name suggests, this method will be executed after the end of the entire request, that is, after the dispatcher servlet renders the corresponding view. The main function of this method is to clean up resources.

3.2 implementation example

Direct code:

3.2. 1 @R_ 419_ 2410 @ interceptor class

package com.my.dm.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class TestInterceptor implements HandlerInterceptor {

  private Logger logger =LogManager.getLogger(TestInterceptor.class);

 @Override
 public void afterCompletion(HttpServletRequest arg0,HttpServletResponse arg1,Object arg2,Exception arg3)
   throws Exception {
  // TODO Auto-generated method stub
  logger.error("afterCompletion");
 }

 @Override
 public void postHandle(HttpServletRequest arg0,ModelAndView arg3)
   throws Exception {
  // TODO Auto-generated method stub
  logger.error("postHandle");
 }

 @Override
 public boolean preHandle(HttpServletRequest arg0,Object arg2) throws Exception {
  // TODO Auto-generated method stub
  logger.error("preHandle");
  return true;
 }

}

3.2. 2 corresponding to single interceptor configuration

<!-- 配置拦截器 -->
 <mvc:interceptors>
  <mvc:interceptor>
   <mvc:mapping path="/**" />
   <bean class="com.my.dm.interceptor.TestInterceptor"></bean>
  </mvc:interceptor>
 </mvc:interceptors>

3.2. 3 configuration of multiple interceptors

<mvc:interceptors>
  <mvc:interceptor>
   <mvc:mapping path="/employee/**" />
   <mvc:mapping path="/trainning/**" />
   <mvc:mapping path="/manage/**" />
   <mvc:exclude-mapping path="/**/fonts/*" />
   <mvc:exclude-mapping path="/**/*.css" />
   <mvc:exclude-mapping path="/**/*.js" />
   <mvc:exclude-mapping path="/**/*.png" />
   <mvc:exclude-mapping path="/**/*.gif" />
   <mvc:exclude-mapping path="/**/*.jpg" />
   <mvc:exclude-mapping path="/**/*.jpeg" />
   <bean class="com.pmo.interceptor.PageInterceptor" />
  </mvc:interceptor>
  <mvc:interceptor>
    <mvc:mapping path="/**"/>
    <bean class="com.pmo.interceptor.LoginInterceptor"></bean>
  </mvc:interceptor>
  <mvc:interceptor>
    <mvc:mapping path="/**"/>
    <bean class="com.pmo.interceptor.UserAuthorityInterceptor"></bean>
  </mvc:interceptor>
 </mvc:interceptors>

The above is the whole content of this article. I hope it will help you in your study, and I hope you will support us a lot.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>