溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

SpringBoot如何注冊(cè)Servlet、Filter、Listener的幾種方式

發(fā)布時(shí)間:2020-09-06 09:07:00 來(lái)源:腳本之家 閱讀:299 作者:技術(shù)小能手 欄目:編程語(yǔ)言

在Servlet 3.0之前都是使用web.xml文件進(jìn)行配置,需要增加Servlet、Filter或者Listener都需要在web.xml增加相應(yīng)的配置。Servlet 3.0之后可以使用注解進(jìn)行配置Servlet、Filter或者Listener;springboot也提供了使用代碼進(jìn)行注冊(cè)Servlet、Filter或者Listener。所以springboot有兩種方式進(jìn)行Servlet、Filter或者Listener配置。

方式一:使用注解

(1)注冊(cè)Servlet

使用@WebServlet注冊(cè),需要在Servlet類上使用該注解即可,但是需要在@Configuration類中使用Spring Boot提供的注解@ServletComponentScan掃描注冊(cè)相應(yīng)的Servlet。

(2)  注冊(cè)Filter

使用@WebFilter注冊(cè),需要在Filter類上使用該注解即可,但是需要在@Configuration類中使用Spring Boot提供的注解@ServletComponentScan掃描注冊(cè)相應(yīng)的Filter。

(3)注冊(cè)Listener

使用@WebListener注冊(cè),需要在Filter類上使用該注解即可,但是需要在@Configuration類中使用Spring Boot提供的注解@ServletComponentScan掃描注冊(cè)相應(yīng)的Listener。

方式二:使用spring提供的方式

(1)注冊(cè)Servlet

使用ServletRegistrationBean注冊(cè)只需要在@Configuration類中加入類似以下的代碼

@Bean
public ServletRegistrationBean regServlet() {
    ServletRegistrationBean userServlet= new ServletRegistrationBean();
    userServlet.addUrlMappings("/servlet");
    userServlet.setServlet(new UserServlet());
    return userServlet;

}

(2)  注冊(cè)Filter

使用FilterRegistrationBean注冊(cè)Filter,只需要在@Configuration類中加入類似以下的代碼:

@Bean
  public FilterRegistrationBean regFilter() {
    FilterRegistrationBean userFilter = new FilterRegistrationBean();
    userFilter .addUrlPatterns("/*");
    userFilter .setFilter(new UserFilter ());
    return userFilter ;

}

(3)注冊(cè)Listener

使用ServletListenerRegistrationBean注冊(cè)Listener只需要在@Configuration類中加入類似以下的代碼:

@Bean
  public ServletListenerRegistrationBean<LoginSessionListener> regServletListener() {
    ServletListenerRegistrationBean<LoginSessionListener> loginSessionListener= new ServletListenerRegistrationBean<LoginSessionListener>();
    loginSessionListener.setListener(new LoginSessionListener());
    return loginSessionListener;

}

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI