Spring boot 自定义拦截器

Posted cosmo

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring boot 自定义拦截器相关的知识,希望对你有一定的参考价值。

1.新建一个类实现HandlerInterceptor接口,重写接口的方法

 1 package com.zpark.interceptor;
 2 
 3 import com.zpark.tools.Constants;
 4 import com.zpark..tools.utils.EmptyUtils;
 5 import org.slf4j.Logger;
 6 import org.slf4j.LoggerFactory;
 7 import org.slf4j.MDC;
 8 import org.springframework.stereotype.Component;
 9 import org.springframework.util.StringUtils;
10 import org.springframework.web.servlet.HandlerInterceptor;
11 import org.springframework.web.servlet.ModelAndView;
12 import javax.servlet.http.HttpServletRequest;
13 import javax.servlet.http.HttpServletResponse;
14 @Component
15 public class CommonInterceptor implements HandlerInterceptor {
16 
17     private Logger log = LoggerFactory.getLogger(CommonInterceptor.class);
18 
19     @Override
20     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
21      log.info("自定义拦截器"); return true;
34     }
35 
50     @Override
51     public void postHandle(HttpServletRequest request,HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception {
52         if(StringUtils.isNotEmpty(modelAndView)) {
53             modelAndView.addObject("resultCode", "100");
54         }
55     }
56     @Override
57     public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
58 
59     }
60 
61 }

2.入口类的目录或者兄弟目录下新建一个类继承WebMvcConfigurerAdapter类并重写addInterceptors方法

package com.zpark;

import com.zpark.interceptor.CommonInterceptor;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; /** * @author cosmo * @Title: * @ProjectName * @Description: TODO * @date */ @Configuration public class MySpringBootConfigurerAdapter extends WebMvcConfigurerAdapter { @Autowired private CommonInterceptor commonInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(commonInterceptor).addPathPatterns("/**"); } }

至此,拦截器配置完毕,可以启动下服务看下效果;



以上是关于Spring boot 自定义拦截器的主要内容,如果未能解决你的问题,请参考以下文章

spring boot 使用拦截器 实现 用户登录拦截

spring-boot添加自定义拦截器

spring boot框架学习8-干货spring boot的web开发-自定义拦截器处理权限

Spring boot 自定义拦截器

250.Spring Boot+Spring Security:基于URL动态权限:自定义AccssDesionManager

Spring Boot中Spring MVC的整合支持