SpringBoot中拦截器接口:
public interface HandlerInterceptor {
default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return true;
}
default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
}
default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
}
}
执行顺序:
preHandle -> controller中的目标方法 -> postHandle -> afterCompletion(请求处理完成之后)
拦截器设置流程:
1、拦截器的业务逻辑
需要实现HandlerInteceptor接口
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
Object loginUser = session.getAttribute("loginUser");
if(loginUser!=null){
return true;
}
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
2、把配置放在容器中
//配置web功能的都需要实现WebMvcConfigurer,
@Configuration
public class AdminWebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/","/login","/css/**","/fonts/**","/images/**","/js/**");
}
}
WebMvcConfigurer接口中有许多web功能:
public interface WebMvcConfigurer {
default void addInterceptors(InterceptorRegistry registry) {
}
default void addResourceHandlers(ResourceHandlerRegistry registry) {
}
default void addCorsMappings(CorsRegistry registry) {
}
default void addViewControllers(ViewControllerRegistry registry) {
}
default void configureViewResolvers(ViewResolverRegistry registry) {
}
default void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
}
default void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> handlers) {
}
default void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
}
......
增加拦截路径和排除拦截路径:
registry.addInterceptor(new LoginInterceptor())
.addPathPatterns("/**") //会拦截所有的请求,也包括静态资源
.excludePathPatterns("/","/login","/css/**","/fonts/**","/images/**","/js/**");
记录一下/**和/*的区别:
SpringMVC 拦截器拦截 /* 和 /** 的区别:_Simba1949的博客-CSDN博客
实验:
将静态资源下的 fonts文件和css文件中设置为/*,然后看访问时候能否放行:
首先是css下的文件:
css下没有任何文件夹了,直接都是文件,按链接里的解释,是可以访问到的。
接着测试fonts文件夹下,按链接意思应该是会被拦截的:
所以很明确了:xxx/*的范围只是针对到xxx/ 下的所有文件,不会包含文件夹
xxx/**的范围就是 xxx/ 下的所有文件夹和文件。