Spring及Springboot中使用拦截器

Spring及Springboot中使用拦截器,第1张

Spring及Springboot中使用拦截

开发流程

Maven依赖servlet-api

  javax.servlet
  javax.servlet-api
  4.0.1
  provided

实现HandlerInterceptor
public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        return false;
    }

    @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 {

    }
}
SpringMVC配置过滤地址
过滤器不受这个标签限制



  
    
    //排除静态资源
    
    
  

SpringBoot中使用拦截器

Springboot中使用拦截器,只需要加入web启动依赖。

还是要实现HandlerInterceptor,只不过在配置的时候有所不同。

新建配置类实现WebMvcConfigurer

@Configuration
public class MyAppConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //创建拦截器对象
        MyInterceptor interceptor=new MyInterceptor();
        //指定拦截的uri
        String[] path ={"/user/**"};
        //不拦截的uri
        String[] excludePath ={"/user/login"};
        registry.addInterceptor(interceptor).
                addPathPatterns(path).
                excludePathPatterns(excludePath);
    }
}
多拦截器执行顺序

使用拦截器前置保存用户访问信息

使用logback日志保存

加入依赖


  ch.qos.logback
  logback-classic
  1.2.5

logback配置文件



    
        
            [%thread] %d %level %logger{10} - %msg%n
        
    
    
        
            d:/logs/history.%d.log
        
        
            [%thread] %d %level %logger{10} - %msg%n
        
    
    
        
    
    
        
    

拦截器类

package com.imooc.restful.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AccessHistoryInterceptor implements HandlerInterceptor {
    private Logger logger = LoggerFactory.getLogger(AccessHistoryInterceptor.class);

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        StringBuilder log = new StringBuilder();
        log.append(request.getRemoteAddr());
        log.append("|");
        log.append(request.getRequestURL());
        log.append("|");
        log.append(request.getHeader("user-agent"));
        logger.info(log.toString());
        return true;
    }
}

springmvc配置拦截规则


  
    
    
    
  

SpringMVC处理流程

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5523253.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-13
下一篇 2022-12-13

发表评论

登录后才能评论

评论列表(0条)

保存