如何在Spring Boot中添加过滤器类?

如何在Spring Boot中添加过滤器类?

我想知道,如果Filter在Spring Boot中有一个类(用于Web应用程序)的注释?也许@Filter吧?

我想在我的项目中添加自定义过滤器。

Spring Boot Reference Guide提到了 FilterRegistrationBean,但我不知道如何使用它。


catspeake
浏览 856回答 3
3回答

潇潇雨雨

如果要设置第三方过滤器,可以使用FilterRegistrationBean。例如,相当于web.xml<filter> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<filter-name>SomeFilter</filter-name> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<filter-class>com.somecompany.SomeFilter</filter-class></filter><filter-mapping> &nbsp;&nbsp;&nbsp;&nbsp;<filter-name>SomeFilter</filter-name> &nbsp;&nbsp;&nbsp;&nbsp;<url-pattern>/url/*</url-pattern> &nbsp;&nbsp;&nbsp;&nbsp;<init-param> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<param-name>paramName</param-name> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<param-value>paramValue</param-value> &nbsp;&nbsp;&nbsp;&nbsp;</init-param></filter-mapping>这些将是您@Configuration文件中的两个bean@Beanpublic&nbsp;FilterRegistrationBean&nbsp;someFilterRegistration()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;FilterRegistrationBean&nbsp;registration&nbsp;=&nbsp;new&nbsp;FilterRegistrationBean(); &nbsp;&nbsp;&nbsp;&nbsp;registration.setFilter(someFilter()); &nbsp;&nbsp;&nbsp;&nbsp;registration.addUrlPatterns("/url/*"); &nbsp;&nbsp;&nbsp;&nbsp;registration.addInitParameter("paramName",&nbsp;"paramValue"); &nbsp;&nbsp;&nbsp;&nbsp;registration.setName("someFilter"); &nbsp;&nbsp;&nbsp;&nbsp;registration.setOrder(1); &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;registration;}&nbsp;public&nbsp;Filter&nbsp;someFilter()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;new&nbsp;SomeFilter();}以上是用spring-boot 1.2.3测试的

RISEBY

没有特殊的注释来表示servlet过滤器。您只需声明一个@Bean类型Filter(或FilterRegistrationBean)。一个示例(向所有响应添加自定义标头)在Boot自己的EndpointWebMvcAutoConfiguration中&nbsp;;如果您只声明Filter它,它将应用于所有请求。如果还添加了a&nbsp;FilterRegistrationBean,则可以另外指定要应用的各个servlet和url模式。注意:从Spring Boot 1.4开始,FilterRegistrationBean不会弃用并简单地将包org.springframework.boot.context.embedded.FilterRegistrationBean移到org.springframework.boot.web.servlet.FilterRegistrationBean
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java