谈一下Interceptor(拦截器)

Interceptor(拦截器) 类似于Filter(过滤器),都是AOP思想的体现,能够实现日志,过滤等处理.

1.拦截器的实现:
  方法一:
         ①导入spring相关的包,实现HandlerInterceptor接口.
         ②在springmvc.xml中注册Interceptor(注意拦截的mapping要写在拦截器bean之前,不然xml一直报错)

Interceptor1.java

package com.wantao.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import lombok.extern.slf4j.Slf4j;

/**
 * @author wantao
 * @date 2019-05-23 4:28:29 PM
 * @description talk is cheap,show me your code
 */
@Slf4j
public class Interceptor1 implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		log.info("interceptor1 preHandle");
		return true;//这里如果不return true则不会执行其余两个方法
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		log.info("interceptor1 postHandle");
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		log.info("interceptor1 afterCompletion");
	}

}

```xml
<font color="red">springmvc.xml</font>
```<context:component-scan base-package="com.wantao.controller"></context:component-scan>
	<mvc:interceptors>
		<mvc:interceptor>
		    <!-- 这里注意一定要先定义mapping再定义bean -->
			<mvc:mapping path="/hello" />
			<mvc:exclude-mapping path="/hello1"/>
			<bean class="com.wantao.interceptor.Interceptor1" />
		</mvc:interceptor>
		<mvc:interceptor>
		    <!-- 这里注意一定要先定义mapping再定义bean,不然xml文件一直报错-->
			<mvc:mapping path="/hello" />
			<mvc:exclude-mapping path="/hello1"/>  <!--排除不要拦截的路径-->
			<bean class="com.wantao.interceptor.Interceptor2" />
		</mvc:interceptor>
	</mvc:interceptors>

  方法二(Springboot):
         ①导入spring相关的包,实现HandlerInterceptor接口.
         ②配置类实现WebMvcConfigurerAdapter接口

2.拦截器的拦截过程
谈一下Interceptor(拦截器)_第1张图片
谈一下Interceptor(拦截器)_第2张图片

3.Interceptor和Filter的一些区别(https://blog.csdn.net/qq_34971162/article/details/80969836)

谈一下Interceptor(拦截器)_第3张图片

你可能感兴趣的:(javaWeb)