尚筹网:登录检查拦截器【拦截器不生效,待解决】

落日映苍穹つ 2023-06-25 03:17 9阅读 0赞

仅仅是临时使用,练习拦截器。将来使用SpringSecurity后将取消。

拦截器类

所在工程:atcrowdfunding-admin-2-component
全类名:com.atguigu.crowd.funding.interceptor.LoginInterceptor

  1. package com.atguigu.crowd.funding.interceptor;
  2. import javax.servlet.http.HttpServletRequest;
  3. import javax.servlet.http.HttpServletResponse;
  4. import javax.servlet.http.HttpSession;
  5. import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
  6. import com.atguigu.crowd.funding.entity.Admin;
  7. import com.atguigu.crowd.funding.util.CrowdFundingConstant;
  8. public class LoginInterceptor extends HandlerInterceptorAdapter {
  9. // 在操作之前请登录, 但是不要拦截登录页面,登出页面
  10. public boolean preHandler(HttpServletRequest request,
  11. HttpServletResponse response,
  12. Object handler) throws Exception{
  13. // 通过request对象获取HttpSession对象
  14. HttpSession session = request.getSession();
  15. // 从Session域尝试获取已登录用户对象
  16. Admin admin = (Admin) session.getAttribute(CrowdFundingConstant.ATTR_NAME_LOGIN_ADMIN);
  17. // 如果没有获取到Admin对象
  18. if(admin == null) {
  19. // 将提示消息存入request域
  20. request.setAttribute(CrowdFundingConstant.ATTR_NAME_MESSAGE, CrowdFundingConstant.MESSAGE_ACCESS_DENIED);
  21. // 转发到登录页面
  22. request.getRequestDispatcher("/WEB-INF/admin-login.jsp").forward(request, response);
  23. return false;
  24. }
  25. // 如果admin对象有效,则放行继续执行后续操作
  26. return true;
  27. }
  28. }

注册拦截器类

所在工程:atcrowdfunding-admin-1-webui
配置文件:spring-web-mvc.xml

  1. <!-- 配置拦截器 -->
  2. <mvc:interceptors>
  3. <mvc:interceptor>
  4. <!-- 设置当前拦截器要拦截的路径 -->
  5. <mvc:mapping path="/**"/>
  6. <!-- 设置要拦截的路径中的例外,也就是不拦截的路径 -->
  7. <mvc:exclude-mapping path="/admin/to/login/page.html"/>
  8. <mvc:exclude-mapping path="/admin/do/login.html"/>
  9. <mvc:exclude-mapping path="/admin/logout.html"/>
  10. <!-- 拦截器的bean -->
  11. <bean class="com.atguigu.crowd.funding.interceptor.LoginInterceptor"/>
  12. </mvc:interceptor>
  13. </mvc:interceptors>

检查拦截器是否生效
1、在拦截器方法中添加打印
2、配置拦截所有

发表评论

表情:
评论列表 (有 0 条评论,9人围观)

还没有评论,来说两句吧...

相关阅读