Oleg
Oleg

Reputation: 1559

Practice for dividing properly work between Spring Controllers

I'm new to web development so please bear with my misunderstandings .

Let's have the following example :

A user wants to perform these operations : login, logout, add 2 numbers, write a comment.

From my current knowledge I would create 4 Controller classes like :

loginController,logoutController, ArithmethicController, TextController.

In these controllers I would to then all the required mappings but : the things like really adding 2 numbers, write comments... must be done by other classes like AdditionClass, WriteTextToSourceClass, UserAuthClass right ?

Furthermore, the AdditionClass, WriteTextToSourceClass, UserAuthClass should extend the HttpServlet probably.

What bugs me, is that I don't know where this Servlet thing comes into play and what is it really used/responsible for if I already divided the work between Controllers, so what work is left for my servlets here ?

Upvotes: 0

Views: 345

Answers (1)

Jack Flamp
Jack Flamp

Reputation: 1233

Spring uses the Dispatcher Servlet that you define in web.xml. Thanks to this you can focus on just creating the controllers. @Controller means that Spring will find your mappings. In your example with just the 4 methods it seems to be overkill to have more than one controller. However in Java generally it is good practice to divide tasks as OO as possible of course. The actual work to be done that you mention usually goes in @Service classes and not extend Servlet. So forget about creating your own Servlets and just work with Controllers, Services and Daos (for CRUD operations, the model i.e).

in web.xml:

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

These tutorials really helped me get started: https://www.gontu.org/spring-framework-tutorials/

Upvotes: 1

Related Questions