今天就跟大家聊聊有关filter如何在Spring Boot中使用,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
过滤器(Filter)的注册方法和 Servlet 一样,有两种方式:代码注册或者注解注册
1.代码注册方式
通过代码方式注入过滤器
@Bean public FilterRegistrationBean indexFilterRegistration() { FilterRegistrationBean registration = new FilterRegistrationBean(new IndexFilter()); registration.addUrlPatterns("/"); return registration; }
IndexFilter.Java类:
package com.example.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; public class IndexFilter implements Filter{ @Override public void destroy() { System.out.println("filter destroy method"); } @Override public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException { System.out.println("filter doFilter method"); } @Override public void init(FilterConfig arg0) throws ServletException { System.out.println("filter init method"); } }
2.注解方式
通过注解方式注入过滤器
IndexFilter2.java类
package com.example.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; @WebFilter(urlPatterns = "/*", filterName = "indexFilter2") public class IndexFilter2 implements Filter{ @Override public void destroy() { System.out.println("filter2 destroy method"); } @Override public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException { System.out.println("filter2 doFilter method"); } @Override public void init(FilterConfig arg0) throws ServletException { System.out.println("filter2 init method"); } }
把注解加到入口处启动即可
@SpringBootApplication @ServletComponentScan public class SpringBootSimpleApplication { public static void main(String[] args) { SpringApplication.run(SpringBootSimpleApplication.class, args); } }
看完上述内容,你们对filter如何在Spring Boot中使用有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。