Spring自定义拦截器
Lequal 人气:01、创建自定义拦截器类(UserTokenInterceptor)并实现HandlerInterceptor 接口,再重写方法,代码如下:
public class UserTokenInterceptor implements HandlerInterceptor { /** * @description 访问Controller之前执行 */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { log.info("进入拦截器啦、、"); return true; // true即可放行,false则不放行 } /** * @description 请求访问Controller之后,渲染视图之前 */ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } /** * @description 请求访问Controller之后,渲染视图之后 */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
2、配置Web拦截器(WebMvcConfig)并实现Spring的WebMvcConfigurer接口
在Spring Boot 1.5版本都是靠重写WebMvcConfigurerAdapter的方法来添加自定义拦截器,消息转换器等。SpringBoot 2.0 后,该类被标记为@Deprecated(弃用)。官方推荐直接实现WebMvcConfigurer或者直接继承WebMvcConfigurationSupport,方式一实现WebMvcConfigurer接口(推荐)
复写addInterceptors方法,添加自己的拦截器
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { // 注册拦截器 registry.addInterceptor(getUserTokenInterceptor()).addPathPatterns("/index/session"); // 一定要加 WebMvcConfigurer.super.addInterceptors(registry); } // @Bean public UserTokenInterceptor getUserTokenInterceptor() { return new UserTokenInterceptor(); } }
3、编写测试Controller
@RestController @RequestMapping("/index") public class IndexController { @Deprecated @GetMapping("/session") public Object getSession(HttpServletRequest request) { HttpSession session = request.getSession(); session.setAttribute("name", "lequal"); session.setMaxInactiveInterval(3600); String name = (String) session.getAttribute("name"); System.out.println("获取的名字是:" + name); return name; } }
4、访问URL地址
如果preHandle方法中return false的话浏览器访问是看不到返回的内容的,因为被拦截住了,就相当于卡在那里了。
加载全部内容