拦截器可以获取IOC容器中的各个bean,拦截器是基于java的反射机制的,拦截器只能对action请求起作用,拦截器可以访问action上下文、值栈里的对象,但无法获取参数。
一、实现HandlerInterceptor接口
package com.wt.cloud.filter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
@Component
public class MyInterceptor implements HandlerInterceptor{
/**
* 功能描述: 执行方法前
* @return : boolean
* @author : big uncle
* @date : 2019/10/9 12:24
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.info("执行方法前");
return false;
}
/**
* 功能描述: 执行方法后,有异常不执行
* @return : boolean
* @author : big uncle
* @date : 2019/10/9 12:24
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
log.info("执行方法后,有异常不执行");
}
/**
* 功能描述: 执行完一定会执行
* @return : boolean
* @author : big uncle
* @date : 2019/10/9 12:24
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
log.info("执行完一定会执行");
}
}
二、注册到InterceptorRegistration
package com.wt.cloud.config;
import com.wt.cloud.filter.MyInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class InterceptorConfig implements WebMvcConfigurer{
@Override
public void addInterceptors(InterceptorRegistry registry) {
//註冊TestInterceptor拦截器 new 或者 注入 都行
InterceptorRegistration registration = registry.addInterceptor(new MyInterceptor());
//所有路径都被拦截
registration.addPathPatterns("/**");
//添加不拦截路径
registration.excludePathPatterns("/","/error","/static/**");
}
}