登录成功后将用户存入session
@ResponseBody @PostMapping("/login") public String login(User user, HttpServletRequest request) { HttpSession session = request.getSession(); if(user.getUsername().equals("bob") && user.getPassword().equals("123")) { session.setAttribute("user",user); return "登录成功"; } else { return "登录失败"; } }2.编写拦截器
检查session中用户是否为空,不为空放行,为空跳转到登录界面
public class LoginInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String requestURI = request.getRequestURI(); System.out.println("请求的路径为:" + requestURI); HttpSession session = request.getSession(); Object user = session.getAttribute("user"); if(user != null) { return true; } request.setAttribute("msg","请先登录~"); request.getRequestDispatcher("/").forward(request, response); return false; } @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 { } }3.将拦截器注入容器
注:服务器内部转发也会经过拦截器
@Configuration public class AdminMvcConfiguration implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new LoginInterceptor()) .addPathPatterns(" .excludePathPatterns("/","/login","/res/**"); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)