拦截器
概念
拦截器有嘛用?
在用户登录时,防止页面跳转
代码
@Controller
public class mapper1 {
@GetMapping("/")//
public String skip(){
return "index";
}
@GetMapping("/login")
public String false1(HttpServletRequest req){
HttpSession session = req.getSession();
session.setAttribute("user",1);
return "false";
}
}
public class AdminInterceptor1 implements HandlerInterceptor {//继承HandlerInterceptor
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String user = (String)request.getSession().getAttribute("user");
if(user!=null){//判读用户是不是已经登录
return true;
}
response.sendRedirect(request.getContextPath()+"/login");//没登录跳转到/login
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
}
@Configuration
public class LoginConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
InterceptorRegistration regiest = registry.addInterceptor(new AdminInterceptor1());
regiest.addPathPatterns("/**");//拦截所有路径
regiest.excludePathPatterns( "/login"); //不拦截
}
}
用心做~