Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I register a secondary servlet with Spring Boot?

I have an extra servlet I need to register in my application. However with Spring Boot and its Java Config, I can't just add servlet mappings in a web.xml file.

How can I add additional servlets?

like image 624
checketts Avatar asked Jan 04 '14 01:01

checketts


People also ask

Can we have two dispatcher servlet?

You can have as many DispatcherServlets as you want. Basically what you need to do is duplicate the configuration and give the servlet a different name (else it will overwrite the previous one), and have some separate configuration classes (or xml files) for it.

Can we use servlet in spring boot?

4.2. In a Spring Boot application, the servlet is registered either as a Spring @Bean or by scanning the @WebServlet annotated classes with an embedded container. With the Spring @Bean approach, we can use the ServletRegistrationBean class to register the servlet.

Can we have multiple servlets in web xml?

You can declare multiple servlets using the same class with different initialization parameters. The name for each servlet must be unique across the deployment descriptor. The <servlet-mapping> element specifies a URL pattern and the name of a declared servlet to use for requests whose URL matches the pattern.


2 Answers

Also available is the ServletRegistrationBean

@Bean public ServletRegistrationBean servletRegistrationBean(){     return new ServletRegistrationBean(new FooServlet(),"/someOtherUrl/*"); } 

Which ended up being the path I took.

like image 136
checketts Avatar answered Sep 22 '22 15:09

checketts


Just add a bean for the servlet. It'll get mapped to /{beanName}/.

@Bean public Servlet foo() {     return new FooServlet(); } 
like image 45
chrylis -cautiouslyoptimistic- Avatar answered Sep 19 '22 15:09

chrylis -cautiouslyoptimistic-