ToB企服应用市场:ToB评测及商务社交产业平台

标题: SpringMVC-08-拦截器 [打印本页]

作者: 王柳    时间: 2024-12-8 21:26
标题: SpringMVC-08-拦截器
1、拦截器概述

SpringMVC的处置惩罚器拦截器 类似于Servlet开发中的过滤器 Filter ,用于对 Handler 举行预处置惩罚后处置惩罚。开发者可以本身定义一些拦截器来实现特定的功能。
过滤器与拦截器的区别:
拦截器是AOP思想的详细应用!

2、拦截器使用

自定义拦截器

那如何实现拦截器呢?
想要自定义拦截器,必须实现 HandlerInterceptor 接口
  1. public interface HandlerInterceptor {
  2.         default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
  3.                         throws Exception {
  4.                 return true;
  5.         }
  6.         default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
  7.                         @Nullable ModelAndView modelAndView) throws Exception {
  8.         }
  9.         default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,@Nullable Exception ex) throws Exception {
  10.         }
  11. }
复制代码
自定义拦截器 MyInterceptor
  1. public class MyInterceptor implements HandlerInterceptor {
  2.     public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
  3.         System.out.println("------------preHandle------------");
  4.         return !"false".equals(httpServletRequest.getParameter("status"));
  5.     }
  6.     public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
  7.         System.out.println("------------postHandle------------");
  8.     }
  9.     public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
  10.         System.out.println("------------afterCompletion------------");
  11.         System.out.println(e);
  12.         if (e != null)
  13.             httpServletRequest.getRequestDispatcher("/").forward(httpServletRequest, httpServletResponse);
  14.     }
  15. }
复制代码
配置拦截器

在Spring的配置文件中定义
  1. <mvc:interceptors>
  2.     <mvc:interceptor>
  3.         
  4.         
  5.         
  6.         <mvc:mapping path="/**"/>
  7.         <mvc:exclude-mapping path="/login"/>
  8.         
  9.         <bean />
  10.     </mvc:interceptor>
  11. </mvc:interceptors>
复制代码
测试

添加Controller
  1. @RestController
  2. public class TestController {
  3.     @RequestMapping("test1")
  4.     public String test1() {
  5.         System.out.println("Handler执行");
  6. //        int i = 1 / 0;
  7.         return "hello";
  8.     }
  9. }
复制代码

3、拦截器执行次序

添加 MyInterceptor2
  1. public class MyInterceptor2 implements HandlerInterceptor {
  2.     public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
  3.         System.out.println("------------preHandle-2------------");
  4.         return true;
  5.     }
  6.     public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
  7.         System.out.println("------------postHandle-2------------");
  8.     }
  9.     public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
  10.         System.out.println("------------afterCompletion-2------------");
  11.     }
  12. }
复制代码
  1. <mvc:interceptors>
  2.     <mvc:interceptor>
  3.         
  4.         
  5.         
  6.         <mvc:mapping path="/**"/>
  7.         <mvc:exclude-mapping path="/login"/>
  8.         
  9.         <bean />
  10.     </mvc:interceptor>
  11. </mvc:interceptors><mvc:interceptors>
  12.     <mvc:interceptor>
  13.         <mvc:mapping path="/**"/>
  14.         <bean id="loginInterceptor" />
  15.     </mvc:interceptor>
  16. </mvc:interceptors>
复制代码
执行测试,观察控制台输出

由图可知,
这好比进入一个有多重门的院子,进去 要先开外门,再开内门,出去 要先开内门,再开外门。

4、验证用户是否登录 (项目案例)

实现思路
编写一个登陆页面 login.jsp
  1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  2. <html>
  3. <head>
  4.     <title>Title</title>
  5. </head>
  6.    
  7. <h1>登录页面</h1>
  8. <hr>
  9.    
  10. <body>
  11. <form action="${pageContext.request.contextPath}/user/login">
  12.     用户名:<input type="text" name="username">
  13.     密码: <input type="password" name="pwd">
  14.     <input type="submit" value="提交">
  15. </form>
  16. </body>
  17. </html>
复制代码
编写一个Controller处置惩罚请求
  1. @Controller
  2. @RequestMapping("/user")
  3. public class UserController {
  4.     //跳转到登陆页面
  5.     @RequestMapping("/jumplogin")
  6.     public String jumpLogin() throws Exception {
  7.         return "login";
  8.     }
  9.     //跳转到成功页面
  10.     @RequestMapping("/jumpSuccess")
  11.     public String jumpSuccess() throws Exception {
  12.         return "success";
  13.     }
  14.     //登陆提交
  15.     @RequestMapping("/login")
  16.     public String login(HttpSession session, String username, String pwd) throws Exception {
  17.         // 向session记录用户身份信息
  18.         System.out.println("接收前端==="+username);
  19.         session.setAttribute("user", username);
  20.         return "success";
  21.     }
  22.     //退出登陆
  23.     @RequestMapping("logout")
  24.     public String logout(HttpSession session) throws Exception {
  25.         // session 过期
  26.         session.invalidate();
  27.         return "login";
  28.     }
  29. }
复制代码
编写一个登陆成功的页面 success.jsp
  1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  2. <html>
  3. <head>
  4.     <title>Title</title>
  5. </head>
  6. <body>
  7.    
  8. <h1>登录成功页面</h1>
  9. <hr>
  10.    
  11. ${user}
  12. <a target="_blank" href="https://www.cnblogs.com/${pageContext.request.contextPath}/user/logout">注销</a>
  13. </body>
  14. </html>
复制代码
在 index 页面上测试跳转!启动Tomcat 测试,未登录也可以进入主页!
  1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  2. <html>
  3.   <head>
  4.     <title>$Title$</title>
  5.   </head>
  6.   <body>
  7.   <h1>首页</h1>
  8.   <hr>
  9.   <%--登录--%>
  10.   <a target="_blank" href="https://www.cnblogs.com/${pageContext.request.contextPath}/user/jumplogin">登录</a>
  11.   <a target="_blank" href="https://www.cnblogs.com/${pageContext.request.contextPath}/user/jumpSuccess">成功页面</a>
  12.   </body>
  13. </html>
复制代码
编写用户登录拦截器
  1. public class LoginInterceptor implements HandlerInterceptor {
  2.     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException {
  3.         // 如果是登陆页面则放行
  4.         System.out.println("uri: " + request.getRequestURI());
  5.         if (request.getRequestURI().contains("login")) {
  6.             return true;
  7.         }
  8.         HttpSession session = request.getSession();
  9.         // 如果用户已登陆也放行
  10.         if(session.getAttribute("user") != null) {
  11.             return true;
  12.         }
  13.         // 用户没有登陆跳转到登陆页面
  14.         request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
  15.         return false;
  16.     }
  17.    
  18.     public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
  19.     }
  20.    
  21.     public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
  22.     }
  23.    
  24. }
复制代码
在Spring的配置文件中注册拦截器
  1. <mvc:interceptors>
  2.     <mvc:interceptor>
  3.         <mvc:mapping path="/**"/>
  4.         <bean id="loginInterceptor" />
  5.     </mvc:interceptor>
  6. </mvc:interceptors>
复制代码
再次重启Tomcat测试!
OK,测试登录拦截功能无误.

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4