這篇文章主要為大家分享在Spring Boot中配置Listener、Filter和Servlet組件的方法。文中還介紹了Spring MVC中使用web.xml文件怕配置Listener、Filter和Servlet組件的方法,希望大家通過這篇文章能有所收獲。
網(wǎng)站建設(shè)哪家好,找成都創(chuàng)新互聯(lián)!專注于網(wǎng)頁(yè)設(shè)計(jì)、網(wǎng)站建設(shè)、微信開發(fā)、小程序定制開發(fā)、集團(tuán)企業(yè)網(wǎng)站建設(shè)等服務(wù)項(xiàng)目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了高碑店免費(fèi)建站歡迎大家使用!
Listener
、Filter
和Servlet
是Java Web開發(fā)過程中常用的三個(gè)組件,其中Filter組件的使用頻率最高,經(jīng)常被用來做簡(jiǎn)單的權(quán)限處理、請(qǐng)求頭過濾和防止XSS
***等。如果我們使用的是傳統(tǒng)的Spring MVC進(jìn)行開發(fā),那么只需要在Tomcat的web.xml文件中進(jìn)行如下配置即可:
org.springframework.web.util.WebAppRootListener
org.springframework.web.context.ContextLoaderListener
filter1
com.csx.MyFilter
filter1
/url/a/*
filter1
/url/b/*
springmvc
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:springmvc.spring.xml
1
springmvc
/
PS:在容器啟動(dòng)的時(shí)候,上面三個(gè)組件啟動(dòng)的順序是Listener --> Filter --> Servlet,這邊安利一個(gè)記憶的方法:把啟動(dòng)順序記憶成“理(Listener)發(fā)(Filter)師(Servlet)”即可。
在web.xml中配置這三個(gè)組件比較簡(jiǎn)單,但是使用Spring-Boot開發(fā)時(shí)使用的是嵌入式容器,并沒有web.xml文件讓我們進(jìn)行配置。在Spring-Boot中到底要怎么配置Listener
、Filter
和Servlet
等組件呢?
這邊我們先來自定義一個(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è)注解一定要加在定義的類上面。
@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í)越高,這樣看起來比較直觀。
另外,Spring還提供了一個(gè)OrderedFilter
接口,這個(gè)接口是Filter
和Ordered
的組合接口,原理和上面的是一樣的。大家可以看情況使用。
上面的這種配置方式優(yōu)點(diǎn)是配置起來非常簡(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`,需要通過`@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`,需要通過`@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
}
}
}
通過 @WebFilter
注解的方式配置Filter簡(jiǎn)單,而且能夠自定義url-pattern和攔截順序。
@Configuration
public class WebConfig {
private static Logger logger = LoggerFactory.getLogger(WebConfig.class);
@Bean
public FilterRegistrationBean filter1() {
FilterRegistrationBean registrationBean = new FilterRegistrationBean<>();
registrationBean.setName("filter1");
registrationBean.setOrder(Ordered.LOWEST_PRECEDENCE - 2);
registrationBean.setFilter(new TimeConsumingCalculationFilter());
registrationBean.addUrlPatterns("/foo/*");
return registrationBean;
}
@Bean
public FilterRegistrationBean filter2() {
FilterRegistrationBean 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");
//通過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ū)別: