我想知道,FilterSpring Boot中的类(对于Web应用程序)是否有任何注释?也许@Filter吧?
FilterSpring Boot
我想在项目中添加自定义过滤器。
《 Spring Boot参考指南 》提到了关于 FilterRegistrationBean,但是我不确定如何使用它。
FilterRegistrationBean
如果您要设置第三方过滤器,则可以使用FilterRegistrationBean。例如相当于web.xml
<filter> <filter-name>SomeFilter</filter-name> <filter-class>com.somecompany.SomeFilter</filter-class> </filter> <filter-mapping> <filter-name>SomeFilter</filter-name> <url-pattern>/url/*</url-pattern> <init-param> <param-name>paramName</param-name> <param-value>paramValue</param-value> </init-param> </filter-mapping>
这些将是@Configuration文件中的两个bean
@Bean public FilterRegistrationBean someFilterRegistration() { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(someFilter()); registration.addUrlPatterns("/url/*"); registration.addInitParameter("paramName", "paramValue"); registration.setName("someFilter"); registration.setOrder(1); return registration; } public Filter someFilter() { return new SomeFilter(); }
上面已经用spring-boot 1.2.3进行了测试
这是在Spring Boot MVC应用程序中包含自定义过滤器的一种方法的示例。确保在组件扫描中包括该软件包:
package com.dearheart.gtsc.filters; 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.http.HttpServletResponse; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; @Component public class XClacksOverhead implements Filter { public static final String X_CLACKS_OVERHEAD = "X-Clacks-Overhead"; @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; response.setHeader(X_CLACKS_OVERHEAD, "GNU Terry Pratchett"); chain.doFilter(req, res); } @Override public void destroy() {} @Override public void init(FilterConfig arg0) throws ServletException {} }