定义一个过滤器类 FirstInterceptor.java:
package com.shuoeasy.springmvc; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; /** * 自定义过滤器类 * */ public class FirstInterceptor implements HandlerInterceptor{ /** * 在目标方法执行之前调用。若返回true则继续走下去。若false则停止 * 场景:可以做权限,日志,事务等 */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("preHandle"); return true; } /** * 在调用目标方法之后,视图渲染之前调用 * 场景:可以修改请求域中的属性、视图进行修改 */ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("postHandle"); } /** * 在渲染视图之后调用 * 场景:可以释放资源 */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("afterCompletion"); } }
springmv.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!-- 配置自动扫描的包 --> <context:component-scan base-package="com.shuoeasy.springmvc"></context:component-scan> <!-- 配置视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 前缀 --> <property name="prefix" value="/WEB-INF/views/"></property> <!-- 文件名 --> <property name="suffix" value=".jsp"></property> </bean> <!-- 自定义拦截器 --> <mvc:interceptors> <bean class="com.shuoeasy.springmvc.FirstInterceptor"></bean> </mvc:interceptors> </beans>
控制器:
package com.shuoeasy.springmvc; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @RequestMapping("/home") @Controller public class Home { /** * 路径 : home/show */ @RequestMapping("/show") public String showPage(){ System.out.println("接收到页面请求"); return "home_index"; } }
控制台输出:
preHandle 接收到页面请求 postHandle afterCompletion