springmvc----拦截器----笔记

定义拦截器
实现HandlerInterceptor接口

package top.demo.test.Interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class MyInterceptor implements HandlerInterceptor{
	
	
	/*
	 * 框架调用doDispatch之前会遍历所有的拦截器 调用其preHandle
	 * 如果某一个拦截器返回false将不执行doDispatch
	 * 
	 * preHandle在方法doDispatch之前调用     
	 * postHandle在处理控制器方法之后 渲染视图之前调用  注意参数有modelAndView可以修改渲染前的数据
	 * afterCompletion在渲染视图之后调用       可以释放资源用
	 * 
	 * 
	 * */
	
	@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");
	}

}

spring配置文件中注册

<?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:aop="http://www.springframework.org/schema/aop"
	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.3.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">


<context:component-scan base-package="top.demo.test"></context:component-scan>

<mvc:annotation-driven></mvc:annotation-driven>

<mvc:interceptors>
	<bean class="top.demo.test.Interceptor.MyInterceptor"></bean>
	
<!-- 
	多个拦截器的执行顺序,preHandle按配置的先后执行,其他两个则按配置先后的反序执行

	还有这种配置方式,指定包含哪些页面路径 (<mvc:mapping path=""/>)或者 排除哪些(<mvc:exclude-mapping path=""/> )
	<mvc:interceptor>
		<mvc:exclude-mapping path=""/> 
		<bean></bean>
		
	</mvc:interceptor>
 -->

	
</mvc:interceptors>
</beans>

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值