1、创建自定义拦截器,实现接口:org.springframework.web.servlet.HandlerInterceptor
package com.hdy.manage.web.interceptor;
import com.hdy.manage.service.SysLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RequestHandlerInterceptor implements HandlerInterceptor {
@Autowired
private SysLogService sysLogService;
/**
* 在Controller处理之前进行调用
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return true;
}
/**
* 在Controller处理之后,在DispatcherServlet进行视图的渲染之前执行
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
/**
* 整个请求完成之后,DispatcherServlet也渲染了视图
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
备注:preHandle方法返回true代表通过拦截器,继续进行处理;返回false代表不通过拦截器,不会继续往下进行处理了。
2、将自定义拦截器添加到拦截器链
package com.hdy.manage.configuration;
import com.hdy.manage.web.interceptor.RequestHandlerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebInterceptorConfiguration implements WebMvcConfigurer {
@Bean
public RequestHandlerInterceptor requestHandlerInterceptor(){
return new RequestHandlerInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(requestHandlerInterceptor()).addPathPatterns("/**");
}
}
- 将自定义拦截器使用@Bean注解生成一个实例对象,由Spring容器管理,可以使拦截器中的注入生效。
- 多个自定义拦截器存在时,registry.addInterceptor添加拦截器的顺序就是拦截器执行的顺序