1.创建一个类实现 HandlerInterceptor 接口,重写接口的方法,添加@Component 注解,这个注解是为后面的使用时进行注入。例:

package com.donlex.mybatiswithspringboot.component;

import com.donlex.mybatiswithspringboot.model.User;
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;

@Component
public class Userhandle implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        //方法执行之前调用拦截
        System.out.println("拦截成功");
		//这里写拦截之后的处理
        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 {

    }
}

2.在入口类的目录或者兄弟目录下创建一个类继承 WebMvcConfigurerAdapter类并重写 addInterceptors 方法;
在该类上方添加注解@SpringBootConfiguration,该 注解表明这是一个配置类

package com.donlex.mybatiswithspringboot.config;
import com.donlex.mybatiswithspringboot.component.Userhandle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@SpringBootConfiguration //添加配置类注解
public class UserLoginConfig extends WebMvcConfigurerAdapter {
    @Autowired
    private Userhandle userhandle;
    @Override
    public void addInterceptors(InterceptorRegistry interceptorRegistry) {
        interceptorRegistry.addInterceptor(userhandle).addPathPatterns("/**");
    }
}

3.项目结构如下:
注意新创建的两个包跟启动类是在同一级的
Spring Boot 实现自定义拦截器

相关文章:

  • 2021-06-09
  • 2018-06-30
  • 2021-07-18
  • 2021-11-15
  • 2021-09-14
猜你喜欢
  • 2018-04-08
  • 2021-08-05
  • 2018-02-07
  • 2021-10-26
  • 2021-10-08
  • 2020-06-30
  • 2021-10-25
  • 2021-09-14
相关资源
相似解决方案