【拦截器】HandlerInterceptor接口

 1 package org.springframework.web.servlet;
 2 
 3 import javax.servlet.http.HttpServletRequest;
 4 import javax.servlet.http.HttpServletResponse;
 5 import org.springframework.web.servlet.ModelAndView;
 6 
 7 public interface HandlerInterceptor {
 8     boolean preHandle(HttpServletRequest var1, HttpServletResponse var2, Object var3) throws Exception;
 9 
10     void postHandle(HttpServletRequest var1, HttpServletResponse var2, Object var3, ModelAndView var4) throws Exception;
11 
12     void afterCompletion(HttpServletRequest var1, HttpServletResponse var2, Object var3, Exception var4) throws Exception;
13 }
View Code

HandlerInterceptor 拦截器有三个方法:preHandlepostHandleafterCompletion

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



拦截器是链式,可以同时存在。执行顺序为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);
    }

}
View Code

 








posted @ 2017-04-28 15:53  爱笑的狐狸  阅读(2317)  评论(0编辑  收藏  举报