【创建定义拦截器规则类】
public class UserInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("---------------------!!!!进入拦截器!!!!------------------------");
//编写业务拦截规则
//从session中获取用户的信息
User user = (User)request.getSession().getAttribute("user");
//判断用户是否登陆
if (null == user){
//未登录
response.sendRedirect(request.getContextPath() +"/User/error");
return false;
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
【创建配置类】
@Configuration //定义为此类为配置类(相当于xml配置文件)
public class IntercrptorConfig implements WebMvcConfigurer {
//重写addInterceptors方法
//mvc:interceptors
@Override
public void addInterceptors(InterceptorRegistry registry) {
//要拦截的请求
String[] addPathPatterns= {
"/User/**"
};
//需要排除的请求
String[] excludePathPatterns = {
"/User/out","/User/login","/User/error"
};
//mvc:interceptor bean class=""
registry.addInterceptor(new UserInterceptor()).addPathPatterns(addPathPatterns).excludePathPatterns(excludePathPatterns);
}
}
【创建Controller层】
@Controller
@RequestMapping(value = "/User")
public class UserController {
@RequestMapping(value = "/login")
public @ResponseBody Object login(HttpServletRequest request){
//将用户信息放入Session中
User user = new User();
user.setId(1001);
user.setUsername("zhangsan");
user.setPassword("123321123321");
request.getSession().setAttribute("user",user);
return "login Success";
}
//该请求需登陆后才能访问
@RequestMapping(value = "/center")
public @ResponseBody Object center(){
return "SEE Center Message";
}
//任何时候都可请求到
@RequestMapping(value = "/out")
public @ResponseBody Object out(){
return "out see anytime";
}
//用户未完成登陆请求了需要登陆才能访问的路径,跳转到该请求
@RequestMapping(value = "error")
public @ResponseBody Object error(){
return "error";
}
}