zoukankan      html  css  js  c++  java
  • springboot拦截器

    先创建一个Interceptor类实现HandlerInterceptor接口

    package ax.tst.interceptor;
    
    import ax.f4j.controller.BaseController;
    import ax.tst.common.AuthTools;
    import ax.tst.model.RequestLog;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.mongodb.core.MongoOperations;
    import org.springframework.stereotype.Component;
    import org.springframework.web.servlet.HandlerInterceptor;
    import org.springframework.web.servlet.ModelAndView;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.util.Date;
    
    /**
     * 请求拦截器
     *
     * @author QQQ
     * @since 2018年5月15日14:51:06
     */
    @Component
    public class RequestInterecptor extends BaseController implements HandlerInterceptor {
    
        @Autowired
        private MongoOperations mongoOperations;
    
        @Autowired
        private AuthTools authTools;
    
        @Override
        public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
            // 记录接口请求日志
            RequestLog requestLog = new RequestLog(authTools.getUserInfo().getId(), getRemoteAddress(), httpServletRequest.getServletPath(), new Date());
            mongoOperations.save(requestLog);
            return true;
        }
    
        @Override
        public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        }
    
        @Override
        public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        }
    }

    注册

    package ax.tst;
    
    import ax.tst.interceptor.RequestInterecptor;
    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;
    
    @Configuration
    public class TstApiConfig extends WebMvcConfigurerAdapter {
    
        @Autowired
        private RequestInterecptor requestInterecptor;
    
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(requestInterecptor).addPathPatterns("/**");
            super.addInterceptors(registry);
        }
    }
  • 相关阅读:
    正则表达式(含递归用法)
    hive tricks
    树的数据结构
    基本排序算法
    佛祖保佑永无BUG
    客户问:“能再便宜点吗”,90%的销售顾问都回答错了?
    AutoMapper的介绍与使用(二)
    AutoMapper的介绍与使用(一)
    hasattr()、getattr()、setattr()函数的使用
    类与对象-内存存储形态
  • 原文地址:https://www.cnblogs.com/dsh2018/p/11263509.html
Copyright © 2011-2022 走看看