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

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

  • 相关阅读:
    POJ 3710 Christmas Game#经典图SG博弈
    POJ 2599 A funny game#树形SG(DFS实现)
    POJ 2425 A Chess Game#树形SG
    LeetCode Array Easy 122. Best Time to Buy and Sell Stock II
    LeetCode Array Easy121. Best Time to Buy and Sell Stock
    LeetCode Array Easy 119. Pascal's Triangle II
    LeetCode Array Easy 118. Pascal's Triangle
    LeetCode Array Easy 88. Merge Sorted Array
    ASP.NET MVC 学习笔记之 MVC + EF中的EO DTO ViewModel
    ASP.NET MVC 学习笔记之面向切面编程与过滤器
  • 原文地址:https://www.cnblogs.com/qinxu/p/10196222.html
Copyright © 2011-2022 走看看