登录拦截器
-
对于管理系统或其他需要用户登录的系统,都需要登录验证,如果没有登录就不行进行相应的操作。
-
SpringBoot 通过实现HandlerInterceptor接口实现拦截器,通过实现WebMvcConfigurer接口实现一个配置类,在配置类中注入拦截器,最后再通过 @Configuration 注解注入配置。
-
实现HandlerInterceptor接口
public class UserLoginInterceptor implements HandlerInterceptor { /*** * 在请求处理之前进行调用(Controller方法调用之前) */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("执行了拦截器的preHandle方法"); try { HttpSession session = request.getSession(); //统一拦截(查询当前session是否存在user)(这里user会在每次登录成功后,写入session) User user = (User) session.getAttribute(USER_LOGIN_STATE); if (user != null) { return true; } //重定向登录页面 response.sendRedirect(request.getContextPath() + "/user/login"); } catch (Exception e) { e.printStackTrace(); } return false; //如果设置为false时,被请求时,拦截器执行到此处将不会继续操作 //如果设置为true时,请求将会继续执行后面的操作 } /*** * 请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后) */ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("执行了拦截器的postHandle方法"); } /*** * 整个请求结束之后被调用,也就是在DispatchServlet渲染了对应的视图之后执行(主要用于进行资源清理工作) */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("执行了拦截器的afterCompletion方法"); } }
-
实现WebMvcConfigurer接口,注册拦截器
@Configuration public class LoginConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { //注册TestInterceptor拦截器 InterceptorRegistration registration = registry.addInterceptor(new UserLoginInterceptor()); //所有路径都被拦截 registration.addPathPatterns("/**"); //添加不拦截路径 registration.excludePathPatterns( "/user/login", "/user/register", "/**/*.html", "/**/*.js", "/**/*.css" ); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)