Spring Boot 实现自定义拦截器

前言

1
个人笔记,仅供备忘

步骤

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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,该 注解表明这是一个配置类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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.项目结构如下:
注意新建的包跟启动类是在同一级

自定义拦截.PNG

0%