@Data
@AllArgsConstructor
public class User {
private Integer id;
private String name;
private Integer age;
}
创建拦截器类,实现HandlerInterceptor接口,重写preHandle方法,在该方法中编写业务拦截的规则
public class UserInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//从session中获取user的信息
User user =(User)request.getSession().getAttribute("user");
//判断用户是否登录
if (null==user){
response.sendRedirect(request.getContextPath()+"/user/error");
return false;
}
return true;
}
}
使用@Configuration注解将这个类定义为配置类,实现WebMvcConfigurer接口并且重写addInterceptors方法
@Configuration//定义此类为配置类
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
//addPathPatterns拦截的路径
String[] addPathPatterns = {
"/user/**"
};
//excludePathPatterns排除的路径
String[] excludePathPatterns = {
"/user/login","/user/noLg","/user/error"
};
//创建用户拦截器对象并指定其拦截的路径和排除的路径
registry.addInterceptor(new UserInterceptor()).addPathPatterns(addPathPatterns).excludePathPatterns(excludePathPatterns);
}
}
@RestController
@RequestMapping("/user")
public class MyController {
//用户登录
@RequestMapping("login")
public Object login(HttpServletRequest request){
//将已经登录的用户信息添加到session中
request.getSession().setAttribute("user",new User(1,"张三",20));
return "Login Success";
}
//不需要登录也能访问的请求
@RequestMapping("/noLg")
public Object noLg(){
return "Everyone Can See";
}
//必须要登录才能访问的请求
@RequestMapping("/mustLg")
public Object mustLg(){
return "Only User Can See";
}
//如果用户未登录访问了需要登录才能访问的请求会跳转到这个错误提示页面
@RequestMapping("/error")
public Object error(){
return "You Must Login";
}
}
点击回车,直接跳转到error界面说明拦截成功
测试其他页面功能
其他页面都能正常访问,在登录成功后再访问mustLg请求
在登录成功后就等正常访问了
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/m0_60117382/article/details/121570141
内容来源于网络,如有侵权,请联系作者删除!