package org.springframework.web.servlet;

 import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView; public interface HandlerInterceptor {
boolean preHandle(HttpServletRequest var1, HttpServletResponse var2, Object var3) throws Exception; void postHandle(HttpServletRequest var1, HttpServletResponse var2, Object var3, ModelAndView var4) throws Exception; void afterCompletion(HttpServletRequest var1, HttpServletResponse var2, Object var3, Exception var4) throws Exception;
}
HandlerInterceptor 拦截器有三个方法:preHandle、postHandle、afterCompletion。

1,preHandle:处理器的预处理,返回true表示流程继续,或者返回结果或者移交给下一个拦截器;返回false表示不会继续处理(流程中断),而是直接response。不会继续调用postHandle和afterCompletion方法。
2,postHandle:后处理回调方法,发生在视图渲染之前。参数ModelAndView可以为空,不为空时会对数据进行处理或者视图渲染。
3,afterCompletion:整个请求处理完毕回调方法,即在视图渲染完毕时回调。

【拦截器】HandlerInterceptor接口-LMLPHP


拦截器是链式,可以同时存在。执行顺序为mvc声明的顺序one by one执行。

拦截器的原理是反射机制,
import com.security.jwt.StatelessAuthenticationInterceptor;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration
public class WebConfig extends WebMvcConfigurerAdapter { @Autowired
private StatelessAuthenticationInterceptor statelessAuthenticationInterceptor; @Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(statelessAuthenticationInterceptor);
} }

05-11 22:36