1.新建一個類實現HandlerInterceptor接口,重寫接口的方法java
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方法web
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