SpringMVC-intercepter配置

    xiaoxiao2026-01-14  8

    springMVC intercepter学习

    Spring的处理器映射支持拦截器。当你想要为某些请求提供特殊功能时,例如对用户进行身份认证,这就非常有用。 处理器映射中的拦截器必须实现org.springframework.web.servlet包中的HandlerInterceptor接口。

    简单示例

    [servlet-name]-servlet.xml配置 主要引入mvc的schema web.xml配置不再叙述。 <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="com.jsu.controller"/> <mvc:interceptors> <mvc:interceptor> <!-- /*拦截当前路径 例如 /add /** 包括路径及其子路径 例如/add/add--> <mvc:mapping path="/**"/> <bean class="com.jsu.intercepter.Intercepter"></bean> </mvc:interceptor> </mvc:interceptors> </beans> intercepter类的编写 主要实现handlerintercepter的三个方法 分别用于处理不同时刻的事件 public class Intercepter implements HandlerInterceptor { /** * 请求方法之前执行 * 如果返回true 那么执行下一个拦截器 否则不执行 */ @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { System.out.println("处理之前"); return true; } /** *执行请求方法之后执行 */ @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { System.out.println("处理之后"); } /** * 在dispatcherservlet之后执行 * 主要是清理工作 */ @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { } }

    3.最后编写controller类

    @Controller public class MainController { @RequestMapping("/intercepter") public String hello(){ System.out.println("hello"); return "index.jsp"; } }

    4.结果如下

    到此我们简单了解了拦截器的处理 以及处理的时间

    最新回复(0)