zoukankan      html  css  js  c++  java
  • 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("/**"); } }

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

  • 相关阅读:
    关于禁用发布可能出现的问题处理
    SQL Server数据库的整理优化的基本过程(一)
    分享SQL2005分区实现教程
    Oracle数据库的测试用户Scott的密码为什么是Tiger?
    这就是传说中的搜狗浏览器2.0
    IE6,IE7下双倍边距续
    IE7下fload:left造成双倍边距BUG
    as2和as3之间交互
    倒计时效果
    js拖动层效果
  • 原文地址:https://www.cnblogs.com/qinxu/p/10196222.html
Copyright © 2011-2022 走看看