SpringMVC-intercepter配置

springMVC intercepter学习

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

简单示例

  1. [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>
  1. 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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值