SpringCloud使用HandlerInterceptor拦截器
作者:互联网
一、编写自定义拦截器SignAutheInterceptor.class
preHandle:在业务处理器处理请求之前被调用。预处理,可以进行编码、安全控制、权限校验等处理;
postHandle:在业务处理器处理请求执行完成后,生成视图之前执行。后处理(调用了Service并返回ModelAndView,但未进行页面渲染),有机会修改ModelAndView (这个博主就基本不怎么用了);
afterCompletion:在DispatcherServlet完全处理完请求后被调用,可用于清理资源等。返回处理(已经渲染了页面);
package com.xiaohang.socialcard.pre.intercepter;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 自定义拦截器
*/
public class SignAutheInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
/**
* 通过HttpServletRequest和HttpServletResponse做相应数据处理
*/
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
二、配置拦截器InterceptorConfig.class
通过addPathPatterns属性可配置需要进行拦截的请求路径
通过excludePathPatterns属性可配置不进行拦截的请求路径
package com.xiaohang.socialcard.pre.intercepter;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* 配置拦截器
*/
@Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new SignAutheInterceptor()).addPathPatterns("/api/v1/get/getToken");
super.addInterceptors(registry);
}
}
标签:拦截器,SpringCloud,springframework,org,import,servlet,public,HandlerInterceptor 来源: https://blog.51cto.com/12012821/2418335