一、新建springboot工程
二、添加实体类
@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 {
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) {
String[] addPathPatterns = {
"/user/**"
};
String[] excludePathPatterns = {
"/user/login","/user/noLg","/user/error"
};
registry.addInterceptor(new UserInterceptor()).addPathPatterns(addPathPatterns).excludePathPatterns(excludePathPatterns);
}
}
五、编写Controller类
@RestController
@RequestMapping("/user")
public class MyController {
@RequestMapping("login")
public Object login(HttpServletRequest request){
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请求 在登录成功后就等正常访问了
|