Home >Java >javaTutorial >Detailed explanation of examples of interceptors in java

Detailed explanation of examples of interceptors in java

Y2J
Y2JOriginal
2017-05-10 10:32:582830browse

This article mainly introduces the simple usage example code of spring boot interceptor. Friends who need it can refer to it

1. The default spring boot interceptor is:

HandlerInterceptorAdapter
AbstractHandlerMapping
UserRoleAuthorizationInterceptor
LocaleChangeInterceptor
ThemeChangeInterceptor

LocaleChangeInterceptor and ThemeChangeInterceptor are more commonly used.

2. Implementing a custom interceptor only requires 3 steps:

1), create our own interceptor class and implement HandlerInterceptor interface.

2), create a Java class Inherit WebMvcConfigurerAdapter, and override the addInterceptors method.

3), instantiate our custom interceptor, and then manually add the object to the interceptor chain (added in the addInterceptors method).

3. Code example

IndexInterceptor.java class code:

package com.example.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class IndexInterceptor implements HandlerInterceptor{
  @Override
  public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
      throws Exception {
    System.out.println(">>>IndexInterceptor>>>>>>>在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)");
  }
  @Override
  public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
      throws Exception {
    System.out.println(">>>IndexInterceptor>>>>>>>请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)");
  }
  @Override
  public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
     System.out.println(">>>IndexInterceptor>>>>>>>在请求处理之前进行调用(Controller方法调用之前)");
     // 只有返回true才会继续向下执行,返回false取消当前请求
     return true;
  }
}

IndexInterceptor2.java class code:

package com.example.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class IndexInterceptor2 implements HandlerInterceptor{
  @Override
  public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
      throws Exception {
    System.out.println(">>>IndexInterceptor2>>>>>>>在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)");
  }
  @Override
  public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
      throws Exception {
    System.out.println(">>>IndexInterceptor2>>>>>>>请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)");
  }
  @Override
  public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
     System.out.println(">>>IndexInterceptor2>>>>>>>在请求处理之前进行调用(Controller方法调用之前)");
     // 只有返回true才会继续向下执行,返回false取消当前请求
     return false;
  }
}

SimpleWebAppConfigurer.java class code:

package com.example.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import com.example.interceptor.IndexInterceptor;
import com.example.interceptor.IndexInterceptor2;
//只要能被springboot扫描到即可
@Configuration
public class SimpleWebAppConfigurer extends WebMvcConfigurerAdapter{
  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    // 多个拦截器组成一个拦截器链
    // addPathPatterns 用于添加拦截规则
    // excludePathPatterns 用户排除拦截
    registry.addInterceptor(new IndexInterceptor()).addPathPatterns("/**");
    registry.addInterceptor(new IndexInterceptor2()).addPathPatterns("/**");
    super.addInterceptors(registry);
  }
}

4. Interceptor parsing description

preHandle**: preprocessing callback method, Implement processor preprocessing (such as login check), and the third parameter is the response processor (such as our Controller implementation in the previous chapter);

Return value: true means continuing the process (such as calling the next Interceptor or processor);

false means that the process is interrupted (such as login check failure), and other interceptors or processors will not continue to be called. At this time, we need to generate a response through response;

postHandle**: Post-processing callback method to implement post-processing of the processor (but before rendering the view). At this time, we can use modelAndView (model and viewobject) to Model data is processed or the view is processed, modelAndView may also be null.

afterCompletion**: Callback method after the entire request is processed, that is, called back when the view is rendered. For example, in performance monitoring, we can record the end time and output the consumption time here, and can also perform some resource cleanup, similar to finally in try-catch-finally, but only calls afterCompletion** of the interceptor whose preHandle returns true in the processor execution chain.

【Related recommendations】

1. Free Java video tutorial

2. Comprehensive analysis of Java annotations

3. FastJson Tutorial Manual

The above is the detailed content of Detailed explanation of examples of interceptors in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn