IT虾米网

Spring boot 自定义拦截器详解

leader 2021年05月27日 编程语言 363 0

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("/**"); } }

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


发布评论
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!

Spring Boot——Linux 启动方式详解
你是第一个吃螃蟹的人
发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。