SpringBoot拦截器的配置
拦截器
- 拦截器是springmvc中的一种,需要实现HandlerInterceptor接口
- 拦截器是拦截用户发起的请求,而后对请求进行做判断处理
- 拦截器是全局的,可以对多个Controller做拦截,一个项目有0个或多个拦截器。它们在一起拦截用户的请求,拦截器长用在:用户登录处理、权限检查、记录日志
拦截器的具体实现
用户登录拦截的简单实现
- 拦截器规则的配置MyInterceptor 去实现HandlerInterceptor 接口
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//编写拦截器规则
//从session中获取用户信息
User user = (User) request.getSession().getAttribute("user");
if (user == null){
response.sendRedirect(request.getContextPath()+"/user/toLogin"); //如果没有登录则跳转去登录
return false;
}else{
return true;
}
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("执行postHandle方法!!!");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("执行afterCompletion!!!");
}
}
- 注入拦截器规则和要拦截路径的配置类InterceptorConfig实现WebMvcConfigurer接口
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
String[] addPathPatterns = {"/user/**"}; //要拦截的路径
String[] excludePathPatterns = {"/user/login","/user/toLogin","/user/viewOrdinary"}; //不拦截的路劲
registry.addInterceptor(new MyInterceptor()) //将登入验证拦截注入
.addPathPatterns(addPathPatterns) //添加拦截路径
.excludePathPatterns(excludePathPatterns); //添加不拦截的路径
}
}
- User实现类
public class User {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
- UserController类
@RestController
@RequestMapping("/user")
public class UserController {
//登录
@RequestMapping("/login")
public String login(HttpServletRequest request){
User user = new User();
user.setId(10001);
user.setName("小夏");
request.getSession().setAttribute("user",user);
return "login success";
}
//查看内容 需登入才能查看
@RequestMapping("/viewContent")
public String viewContent(){
return "This is Content";
}
//未登录时去发起要登录才能进行的请求跳转到这
@RequestMapping("/toLogin")
public String toLogin(){
return "permission denied !!! please login in";
}
//查看普通内容 未登入也能查看
@RequestMapping("/viewOrdinary")
public String viewOrdinary(){
return "This is normal content";
}
}
简单测试
登录过后才能操作的请求
直接能操作的请求
登录请求
登录成功后再次查看viewContent
通过测试可看出简单登录拦截器已经实现