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?
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.
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.
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.
Also available is the ServletRegistrationBean
@Bean public ServletRegistrationBean servletRegistrationBean(){ return new ServletRegistrationBean(new FooServlet(),"/someOtherUrl/*"); }
Which ended up being the path I took.
Just add a bean for the servlet. It'll get mapped to /{beanName}/
.
@Bean public Servlet foo() { return new FooServlet(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With