时尚家居我家的装修小确幸怎么把简约与个性并重
0 2024-11-19
在上一章节中我们讲解了Spring Boot中的基本使用步骤 本次我们将使用来实现 登录状态的拦截判断需求 OK,直接上代码: 首先我们实现一个AdminLoginInterInterceptor ,在用户访问管理端的url时,判断是否为管理员@Componentpublic class AdminLoginInterceptor implements HandlerInterceptor {public static String LOGIN_FLAG = admin;private void printMsg(String msg) {System.out.println([AdminLoginInterceptor] +msg);}@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {printMsg(preHandle);HttpSession session = request.getSession(true);if (session.getAttribute(LOGIN_FLAG) != null) {printMsg(已登录);return true;}// 重定向到登录页面response.sendRedirect(Utils.getHostPath(request) + /admin/loginPage);return true;}@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception {printMsg(postHandle);}@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response,Object handler, Exception exception) throws Exception {printMsg(afterCompletion);}} 写好了,此时就是要将我们的与Spring关联上并告知 如何调用了 通过实现一个WebMvcConfigurer,然后通过addInterceptors方法参数中的注册器注册@Componentpublic class ProductServiceInterceptorAppConfig implements WebMvcConfigurer {@AutowiredPathInterceptor pathInterceptor;@AutowiredAdminLoginInterceptor adminLoginInterceptor;@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(adminLoginInterceptor).addPathPatterns(/admin/**).excludePathPatterns(/admin/login,/admin/loginPage);}} 在login的时候我们将登陆成功后的信息存入session中 通过LOGIN_FLAG作为key即可