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

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

  • 相关阅读:
    001 windows下如何生成公钥和私钥
    函数基础
    各种推导式
    MySQL误删数据
    kafka 学习笔记
    Nginx 功能
    Nginx 到底可以做什么
    Nginx 到底可以做什么
    Shell的18条常用命令整理
    超详细 Nginx 极简教程
  • 原文地址:https://www.cnblogs.com/qinxu/p/10196222.html
Copyright © 2011-2022 走看看