SpringBoot如何自定义拦截器呢?
下文笔者讲述springboot自定义拦截器的方法分享,如下所示
HandlerInterceptor的功能
在request被响应之前(请求到达Controller之前) 在request被响应后视图渲染之前 整个request全部结束之后(一般用于请求结束释放资源) 注意事项: 不能使用拦截器修改request里的内容 但可以抛异常或return false来结束Request请求的后续执行
实现自定义拦截器方法
自定义拦截器类:实现HandlerInterceptor接口package com.java265.myInterceptor; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Component public class MyInterceptor implements HandlerInterceptor { //请求处理之前Controller之前调用 @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { System.out.println("MyInterceptor the requestHandler before"); //必须return:true否则请求将不会向下执行 return true; } //请求处理之后但视图渲染之前调用 @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { System.out.println("MyInterceptor the requestHandler after"); } //整个请求结束,视图完成渲染之后调用,一般用于释放资源 @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { System.out.println("MyInterceptor the view after"); } } 配置自定义拦截器类:创建一个Java类继承WebMvcConfigurerAdapter,并重写 addInterceptors 方法 将自定义拦截器放入拦截器链中:addInterceptors 方法中添加自己的拦截器类,并指定拦截的URL; package com.java265.myInterceptor; import org.springframework.beans.factory.annotation.Autowired; 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 MyInterceptorConfig extends WebMvcConfigurerAdapter { @Autowired private MyInterceptor myInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { //将自定义拦截器加入拦截器链中,并指定拦截的URl registry.addInterceptor(myInterceptor).addPathPatterns("/swagger/*"); } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。