Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why, when and in which case, we should use multiple servlet instead of single servlet in spring mvc?

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.

like image 323
Harry Budianto Avatar asked Dec 17 '25 12:12

Harry Budianto


1 Answers

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.

like image 94
Daniel Lavoie Avatar answered Dec 20 '25 18:12

Daniel Lavoie