Python 官方文档:入门教程 => 点击学习
目录过滤器编写过滤器注册过滤器基于 FilterReGIStrationBean基于 @WEBFilter拦截器过滤器 实现过滤器需要实现 javax.servlet.Filter
实现过滤器需要实现 javax.servlet.Filter
接口。重写三个方法。其中 init()
方法在服务启动时执行,destroy()
在服务停止之前执行。
可用两种方式注册过滤器:
FilterRegistrationBean
来注入。可使用 setOrder(0)
设置过滤器的优先级,越小优先级越高。@WebFilter(filterName = "myFilter2" ,urlPatterns = "
@Component
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(httpservletRequest request, HttpServletResponse response, Object handler) throws Exception {
// handle可拿到执行方法的反射对象。
System.out.println("preHandle: MyInterceptor");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// 对于RESTful 接口用处不大
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// 可捕捉异常,但是SpringBoot已经有了全局异常捕捉
}
}
配置拦截器:
package com.example.recorddemo.configuration;
import com.example.recorddemo.interceptor.MyInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebmvcConfigurer;
import javax.annotation.Resource;
@Configuration
public class InterceptorConfiguration implements WebMvcConfigurer {
@Resource
MyInterceptor myInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myInterceptor).addPathPatterns("/**");
}
}
registry.addInterceptor()
方法会返回当前的 interceptor
, 因此可直接执行 addPathPatterns()
方法
public InterceptorRegistration addInterceptor(HandlerInterceptor interceptor) {
InterceptorRegistration registration = new InterceptorRegistration(interceptor);
this.registrations.add(registration);
return registration;
}
拦截器的执行顺序类似于栈,按照如下顺序执行:
preHandle-1, preHandle-2, postHandle-2, postHandle-1, afterCompletion-2, afterCompletion-1
到此这篇关于SpringBoot过滤器与拦截器深入分析实现方法的文章就介绍到这了,更多相关SpringBoot过滤器与拦截器内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: SpringBoot过滤器与拦截器深入分析实现方法
本文链接: https://lsjlt.com/news/170745.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0