原文链接:java过滤器(Filter – 编程屋 目录 1 过滤器简介 2 Filter详细介绍 3 Filter的用法 3.1 用法1 3.2 用法2 1 过滤器简介 filter也称之为过滤器,它是javaweb三大组件之一(S
原文链接:java过滤器(Filter – 编程屋
目录
filter也称之为过滤器,它是javaweb三大组件之一(Servlet程序、Listener监听器、Filter过滤器)
作用:既可以对请求进行拦截,也可以对响应进行处理。
常见场景:权限检查,日记操作、拦截请求、过滤操作、对请求字符设置编码。
要想介绍filter,就必须介绍Filter中的三个方法。
@Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { } @Override public void destroy() { }
1)自定义一个过滤器实现Filter接口、配置@WEBFilter注解,配置拦截路径(也可通过web.xml配置)
@WebFilter(urlPatterns = " @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println("我是过滤器,我进来了"); } @Override public void destroy() { }}
2)在启动类上加上@ServletComponentScan注解
@SpringBootApplication@ServletComponentScanpublic class springbootInterceptorApplication { public static void main(String[] args) { SpringApplication.run(SpringbootInterceptorApplication.class, args); }}
3)controller:
@RestControllerpublic class LoginController { @GetMapping("/test/filter") public String testFilter(){ return "该请求被拦截了,但是在过滤器中已经放行了"; }}
直接浏览器访问:
控制台输出:发现该请求已经被过滤去拦截
1)自定义一个过滤器实现Filter接口、配置拦截路径(也可通过web.xml配置)
public class MyFilterOne implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println("我是过滤器,我进来了"); filterChain.doFilter(servletRequest, servletResponse); } @Override public void destroy() { }}
2)在启动类上注册
@SpringBootApplicationpublic class SpringbootInterceptorApplication { public static void main(String[] args) { SpringApplication.run(SpringbootInterceptorApplication.class, args); } @Bean public FilterReGIStrationBean getFilterRegistrationBean(){ FilterRegistrationBean bean = new FilterRegistrationBean(new MyFilterOne()); //bean.addUrlPatterns(new String[]{"*.do","*.jsp"}); bean.addUrlPatterns("/*"); return bean; }}
测试结果与3.1相同。
总结:
要想调用配置一个过滤器:
1)启动类上增加注解@ServletComponentScan
2)新建一个类使其实现Filter接口,并实现里面的三个方法
3)在新建类上加上@WebFilter()注解,配置需要拦截的规则
4)在doFilter方法中控制filterChain.doFilter(servletRequest, servletResponse)调用
同样,如果前后端交互有遇到跨域问题的,也可以通过Filter解决(亲测有效),如:
以上只是部分内容,为了维护方便,本文已迁移到新地址:java过滤器(Filter – 编程屋
来源地址:https://blog.csdn.net/qq_50652600/article/details/127308348
--结束END--
本文标题: java过滤器(Filter)
本文链接: https://www.lsjlt.com/news/399092.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-04-03
2024-04-03
2024-04-01
2024-01-21
2024-01-21
2024-01-21
2024-01-21
2023-12-23
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0