1.先创建一般的Controller实体类
UserController.java
package com; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/user") public class UserController { @RequestMapping("/testInterceptor") public String testInterceptor(){ System.out.println("testInterceptor执行了..."); return "success"; } }
2.编写index.jsp
<%-- Created by IntelliJ IDEA. User: My Date: 2021/2/13 Time: 8:53 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <script src="js/jquery.min.js"></script> <body> <h3>拦截器</h3> <a href="user/testInterceptor">拦截器</a> </body> </html
3.拦截器编写 第一步:编写一个普通类实现 HandlerInterceptor 接口
MyInterceptor1.java
package com; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class MyInterceptor1 implements HandlerInterceptor { /** * 预处理,controller方法执行前 * return true 放行,执行下一个拦截器,如果没有,执行controller中的方法 * return false不放行 * @param request * @param response * @param handler * @return * @throws Exception */ public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("MyInterceptor1执行了...前1111"); // request.getRequestDispatcher("/WEB-INF/pages/error.jsp").forward(request,response); return true; } /** * 后处理方法,controller方法执行后,success.jsp执行之前 * @param request * @param response * @param handler * @param modelAndView * @throws Exception */ public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("MyInterceptor1执行了...后1111"); // request.getRequestDispatcher("/WEB-INF/pages/error.jsp").forward(request,response); } /** * success.jsp页面执行后,该方法会执行 * @param request * @param response * @param handler * @param ex * @throws Exception */ public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("MyInterceptor1执行了...最后1111"); } }
第二步:配置拦截器
在springmvc.xml中配置
<!--配置拦截器--> <mvc:interceptors> <!--配置拦截器--> <mvc:interceptor> <!--要拦截的具体的方法--> <mvc:mapping path="/user/*"/> <!--不要拦截的方法 <mvc:exclude-mapping path=""/> --> <!--配置拦截器对象--> <bean class="com.MyInterceptor1" /> </mvc:interceptor> </mvc:interceptors>
测试运行结果:
总结:
preHandle 方法 预处理,controller方法执行前
postHandle 方法 后处理方法,controller方法执行后,success.jsp执行之前
afterCompletion 方法 success.jsp页面执行后,该方法会执行