I start learning Spring MVC yesterday, then I figure that in Spring MVC (or another framework maybe) we can have many servlet in one web apps.
Servlet have a url-pattern that will be matched if there is any http request. In other hand, we can just using @RequestMapping to do a mapping for http request.
So the question is why, when and in which case we should use multiple servlet ?
What is the best practice for that ?
Thank you.
Usually with Spring MVC, you declared a single servlet in web.xml like the following :
<servlet>
<servlet-name>ActivityReplicator</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ActivityReplicator</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
This servlet will be responsible to handle every request to your application and to dispatch them to the right Controller.
Using a single servlet limits the configuration that has to be done in web.xml. Spring Controllers are specially built to handle redirections coming from the DispatcherServlet. As Nathan explained, controllers are less complicated to configure.
I would suggest a Controller for every domain found in your application. For exemple, one controller for user management, another for forum post management. You can read on Restfull controllers using Spring to have an idea of how many controllers to implements.
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