這篇文章主要為大家分享在Spring Boot中配置Listener、Filter和Servlet組件的方法。文中還介紹了Spring MVC中使用web.xml文件怕配置Listener、Filter和Servlet組件的方法,希望大家通過(guò)這篇文章能有所收獲。
網(wǎng)站建設(shè)哪家好,找成都創(chuàng)新互聯(lián)!專(zhuān)注于網(wǎng)頁(yè)設(shè)計(jì)、網(wǎng)站建設(shè)、微信開(kāi)發(fā)、小程序定制開(kāi)發(fā)、集團(tuán)企業(yè)網(wǎng)站建設(shè)等服務(wù)項(xiàng)目。為回饋新老客戶(hù)創(chuàng)新互聯(lián)還提供了高碑店免費(fèi)建站歡迎大家使用!
Listener
、Filter
和Servlet
是Java Web開(kāi)發(fā)過(guò)程中常用的三個(gè)組件,其中Filter組件的使用頻率最高,經(jīng)常被用來(lái)做簡(jiǎn)單的權(quán)限處理、請(qǐng)求頭過(guò)濾和防止XSS
***等。如果我們使用的是傳統(tǒng)的Spring MVC進(jìn)行開(kāi)發(fā),那么只需要在Tomcat的web.xml文件中進(jìn)行如下配置即可:
<!-- 配置Listener -->
<listener>
<listener-class>org.springframework.web.util.WebAppRootListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--配置Filter,這邊配置了一個(gè)Filter,但是匹配了多個(gè)url-pattern-->
<!-- 以u(píng)rl-partern方式配置的filter中,如果有多個(gè)與當(dāng)前請(qǐng)求匹配,則按web.xml中filter-mapping出現(xiàn)的順序來(lái)運(yùn)行-->
<filter>
<filter-name>filter1</filter-name>
<filter-class>com.csx.MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>filter1</filter-name>
<url-pattern>/url/a/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>filter1</filter-name>
<url-pattern>/url/b/*</url-pattern>
</filter-mapping>
<!--配置Servlet-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.spring.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!-- 這邊不建議寫(xiě)成/* -->
<url-pattern>/</url-pattern>
</servlet-mapping>
PS:在容器啟動(dòng)的時(shí)候,上面三個(gè)組件啟動(dòng)的順序是Listener --> Filter --> Servlet,這邊安利一個(gè)記憶的方法:把啟動(dòng)順序記憶成“理(Listener)發(fā)(Filter)師(Servlet)”即可。
在web.xml中配置這三個(gè)組件比較簡(jiǎn)單,但是使用Spring-Boot開(kāi)發(fā)時(shí)使用的是嵌入式容器,并沒(méi)有web.xml文件讓我們進(jìn)行配置。在Spring-Boot中到底要怎么配置Listener
、Filter
和Servlet
等組件呢?
這邊我們先來(lái)自定義一個(gè)Filter,這個(gè)Filter的作用是統(tǒng)計(jì)一個(gè)接口的調(diào)用時(shí)間。
public class TimeConsumingCalculationFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest=(HttpServletRequest)request;
long startTime = System.nanoTime();
logger.info(">>>>>>> Begin ["+httpRequest.getRequestURI()+"]...");
try{
chain.doFilter(request, response);
}finally {
long endTime = System.nanoTime();
logger.info(">>>>>>> End ["+httpRequest.getRequestURI()+"]["+(endTime-startTime)/1000/1000.0+"ms].");
}
}
}
在Spring-Boot中配置上面的Filter,我們只需要在@Configuration
文件中做如下配置即可:
@Configuration
public class WebConfig {
private static Logger logger = LoggerFactory.getLogger(WebConfig.class);
@Bean
public Filter filter1(){
return new TimeConsumingCalculationFilter();
}
}
上面的Filter默認(rèn)會(huì)攔截所有請(qǐng)求。假如我們想要配置多個(gè)攔截器的話,只要再加一個(gè)Bean方法就可以了。
@Configuration
public class WebConfig {
private static Logger logger = LoggerFactory.getLogger(WebConfig.class);
@Bean
public Filter filter1(){
return new TimeConsumingCalculationFilter();
}
@Bean
public Filter filter2() {
return new TimeConsumingCalculationFilter2();
}
}
上面的配置代碼配置了兩個(gè)Filter,兩個(gè)Filter默認(rèn)都會(huì)攔截所有請(qǐng)求,攔截的順序是:filter1-->filter2。這邊的邏輯是先配置的Filter先攔截,后配置的Filter后攔截。當(dāng)然,如果我們想明確指定攔截順序的話可以借助@Order
注解。但是需要注意的是這個(gè)注解一定要加在定義的類(lèi)上面。
@Order(Ordered.LOWEST_PRECEDENCE - 2)
public class TimeConsumingCalculationFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//your logic
}
}
@Order(Ordered.LOWEST_PRECEDENCE - 1)
public class TimeConsumingCalculationFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//your logic
}
}
PS: @Order中的value值越大,執(zhí)行的優(yōu)先級(jí)越小。值越小,優(yōu)先級(jí)越大。當(dāng)我們自定義執(zhí)行順序的時(shí)候,建議使用
@Order(Ordered.LOWEST_PRECEDENCE - 1)
這種形式配置,Ordered.LOWEST_PRECEDENCE減去的值越大,優(yōu)先級(jí)越高,這樣看起來(lái)比較直觀。
另外,Spring還提供了一個(gè)OrderedFilter
接口,這個(gè)接口是Filter
和Ordered
的組合接口,原理和上面的是一樣的。大家可以看情況使用。
上面的這種配置方式優(yōu)點(diǎn)是配置起來(lái)非常簡(jiǎn)單,但是缺點(diǎn)也比較明顯,就是配置不夠靈活,默認(rèn)會(huì)攔截所有請(qǐng)求。
@WebFilter
注解是Servlet中提供的注解,Spring也支持這個(gè)注解。@WebFilter
能進(jìn)行細(xì)粒度的進(jìn)行配置,比上面的方式更加靈活。
@Configuration
public class WebConfig {
//可以自定義url-pattern
@WebFilter(urlPatterns="/*")
@Order(Ordered.LOWEST_PRECEDENCE - 2)
//這邊如果不加`@Configuration`,需要通過(guò)`@ServletComponentScan`掃描`Listener`、`Filter`和`Servlet`這三個(gè)組件
@Configuration
public class TimeConsumingCalculationFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//your logic
}
}
@WebFilter(urlPatterns="/*")
@Order(Ordered.LOWEST_PRECEDENCE - 2)
//這邊如果不加`@Configuration`,需要通過(guò)`@ServletComponentScan`掃描`Listener`、`Filter`和`Servlet`這三個(gè)組件
@Configuration
public class TimeConsumingCalculationFilter2 implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//your logic
}
}
}
通過(guò) @WebFilter
注解的方式配置Filter簡(jiǎn)單,而且能夠自定義url-pattern和攔截順序。
@Configuration
public class WebConfig {
private static Logger logger = LoggerFactory.getLogger(WebConfig.class);
@Bean
public FilterRegistrationBean<Filter> filter1() {
FilterRegistrationBean<Filter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setName("filter1");
registrationBean.setOrder(Ordered.LOWEST_PRECEDENCE - 2);
registrationBean.setFilter(new TimeConsumingCalculationFilter());
registrationBean.addUrlPatterns("/foo/*");
return registrationBean;
}
@Bean
public FilterRegistrationBean<Filter> filter2() {
FilterRegistrationBean<Filter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setName("filter2");
registrationBean.setOrder(Ordered.LOWEST_PRECEDENCE - 3);
registrationBean.setFilter(new TimeConsumingCalculationFilter1());
registrationBean.addUrlPatterns("/*");
registrationBean.addInitParameter("key1","value1");
registrationBean.addInitParameter("key2","value2");
//通過(guò)Servlet name匹配Filter,不建議使用
registrationBean.addServletNames("name1");
return registrationBean;
}
}
注意點(diǎn):
@Configuration
public class WebConfig {
@Bean("myFilter")
//配置了DelegatingFilterProxyRegistrationBean后,這種方式配置的Filter不會(huì)生效了,只會(huì)攔截/foo/*的請(qǐng)求
public Filter myFilter(){
return new TimeConsumingCalculationFilter();
}
@Bean
public DelegatingFilterProxyRegistrationBean delegatingFilterProxyRegistrationBean(){
DelegatingFilterProxyRegistrationBean filterProxy = new DelegatingFilterProxyRegistrationBean("myFilter");
filterProxy.addUrlPatterns("/foo/*");
filterProxy.addInitParameter("targetFilterLifecycle","true");
filterProxy.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico");
filterProxy.setDispatcherTypes(DispatcherType.REQUEST);
return filterProxy;
}
}
FilterRegistrationBean和DelegatingFilterProxyRegistrationBean區(qū)別:
分享名稱(chēng):如何在SpringBoot中配置Listener、Filter和Servlet組件
當(dāng)前鏈接:http://jinyejixie.com/article20/pdcpco.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供電子商務(wù)、定制開(kāi)發(fā)、微信小程序、手機(jī)網(wǎng)站建設(shè)、軟件開(kāi)發(fā)、網(wǎng)頁(yè)設(shè)計(jì)公司
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)