SpringMVC的学习12(springmvc中关于拦截器的应用)

在定义拦截器时需要实现HandlerInterceptor后通过接口中的方法去实现即可
(1)实现接口InterceptorMyInterceptor

public class MyInterceptor implements HandlerInterceptor {
    /**
     * 在处理器处理具体方法之前开始执行
     * @param request
     * @param response
     * @param handler
     * @return 注意返回值,若返回值是false表示请求处理到此为止,如果是true,才会向下执行
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(this.getClass().getName()+"拦截器开始执行");
		//当为true时才会继续执行,如果为false会不再执行后面部分
        return true;
    }

    /**
     * 在处理器完成方法的处理之后执行
     * @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(this.getClass().getName());
    }

    /**
     * 整个servlet处理完成之后才会执行,主要做资源清理的工作
     * @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(this.getClass().getName());
    }
}

(2)xml文件配置,开启拦截器

	<mvc:interceptors>
        <bean class="com.csh.interceptor.MyInterceptor"></bean>
    </mvc:interceptors>

(3)请求的使用,其实定义的拦截器在任何请求中都会调用到,所以这里的Controller并没有什么特殊,普通的请求及返回跳转

@Controller
public class InterceptorController {
    @RequestMapping("/testinterceptor")
    public String interceptor(){
        System.out.println(this.getClass().getName());
        return "success";
    }
}

执行顺序:
preHandle—》目标的方法—》postHandle----》先页面跳转----》afterCompletion
如果执行报异常,那么afterCompletion依然会继续执行
当有多个拦截器时,执行顺序是按照先都执行preHandle后逆序回来执行postHandle

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值