When to use Servlet or @Controller

34,147

Solution 1

If you're a student interested in learning the language then I would stick with servlets for now. It's possible to write a web app using just servlets but in practice you'll probably want to look at JSP's too.

A JSP is a convenient way to write a servlet that allows you to mix html with scripting elements (although it's recommended to avoid Java code in your jsp in favour of tags and el expressions). Under the covers it will be compiled as a servlet but it avoids you having to use lots of messy print statements.

It's important to have at least a basic understanding of servlets and JSP's. Spring MVC is one of many frameworks built on top of servlets to try make the task of writing a web application a bit easier. Basically all requests are mapped to the DispatcherServlet which acts as a front controller.

The DispatcherServlet will then call the controller whose annotations match the incoming request. This is neater than having to write these mappings yourself in the web.xml (although with servlet 3.0 you can annotate servlets now). But you also get many other benefits that can be used like mapping form fields to an object, validating that object with jsr303 annotations, map inputs and outputs to xml or json etc etc. Plus it's tightly integrated with core spring so you can easily wire in your services for the controller to call.

It's worth noting that there are a plethora of competing frameworks built on top of servlets. Spring MVC is one of the most popular so it's not a bad choice to look into.

Solution 2

A Servlet and a Spring MVC Controller can be used to do the same thing but they act on different level of a Java Application

The servlet is a part of the J2EE framework and every Java application server (Tomcat, Jetty, etc) is built for running servlets. Servlet are the "low level" layer in the J2EE stack. You don't need a servlet.jar to run you application because it's prepackaged with the application server

A Spring MVC controller is a library built upon the servlet to make things easier. Spring MVC offers more built-in functionalities such as form parameter to controller method parameter mapping, easier handling of binary form submissions (i.e. when your form can upload files). You need to package the required jars to your application in order to run a Spring MVC Controller

You should use a servlet when you need to go "low level", and example could be for performance reason. Spring MVC performs good but if it has some overhead, if you need to squeeze out all you can from your application server (and you have already tuned the other layers such as the db) go with a servlet. You can choose a servlet if you want to understand the foundation of the J2EE web specifications (i.e. for educational purposes)

In all the other cases you can/should choose a web framework. Spring MVC is one of them; with Spring MVC you don't need to reinvent the wheel (i.e binary form management, form parameter to bean conversion, parameter validation and so on). Another plus of Spring MVC is that in one class you can easily manage input from different urls and methods, doing the same in a servlet is possible but the code is more complicated and less readable. My opinion is that Spring MVC is good for building rest services and managing simple applications (i.e web application with simple forms). If you need to manager very complex forms with Ajax, nested forms, and an application with both session and page state my advice is to switch to a component based framework (like apache wicket for example).

Solution 3

JSF and JSP aswell as Spring MVC builts upon Servlets. The problem this that servlets are not very "nice" to work with because you have to write direct html.

If you are able to use mordern web technologies I would just use servlets in positions that need direct http output like writing an image from a database to http.

Using SpringMVC or JSF which work with a Dipatcherservlet or FacesServlet is just faster and more fun. They parse your files and send it through a servlet.

Share:
34,147
Roger
Author by

Roger

I'm a Java developer, mostly working on enterprise applications/systems. I have a background in PL1, FormScape and .NET (C#) although that is history now. =)

Updated on March 31, 2020

Comments

  • Roger
    Roger about 4 years

    I need to get a few things cleared up. I have been looking for an answer for this one, but I can't seem to find a good answer to my specific questions (eg. this question was nibbling on the answer: Difference between servlet and web service).

    To my understanding, there are different ways you can implement the "request handling", aka "Controller", in an "MVC oriented" web application, two of them being:

    1. A Java specific Servlet (ie. one you create by clicking new -> Servlet, in eclipse for example), used as a "Controller". This one extends HttpServlet and you use methods like doGet and doPost etc.
    2. A Spring MVC annotated @Controller class (yes, using a DispatcherServlet). With this one you use the @RequestMethod GET/POST etc.

    Now to my questions...

    • When do you use one or the other?
    • Are there any general advantages to use one method over the other? (Like, is one method recommended over the other in general?)

    [EDIT]: Emphasized keywords

  • JB Nizet
    JB Nizet almost 11 years
    JPA has nothing to do with servlets. And servlets are usually used in conjunction with JSPs, just as Spring MVC controllers.
  • Lukas Eichler
    Lukas Eichler almost 11 years
    I mean JSP I always write JPA when I mean JSP. sorry.
  • Roger
    Roger almost 11 years
    Nice explanation! I have a basic understanding of how things work individually, it's just that I cannot really put my finger on when to use either methodology. You explained the differences between the two though, without elaborating their actual field of use. Can you name any example of a situation where I would use one method over the other?
  • Roger
    Roger almost 11 years
    @Templar Thanks for answering! I'm still a little bit confused though. What kind of applications would you use @Controller (Spring MVC) for and what kind of applications would you use a "regular servlet" for?
  • Lukas Eichler
    Lukas Eichler almost 11 years
    Everything where I don't need to write to direct httpstream -> @Controller Writing resources like images to httpstream -> Servlet
  • Ben Thurley
    Ben Thurley almost 11 years
    They're both used for the same things (creating web apps). The difference is that Spring MVC adds in lots of convenience. Most people writing a Java web application will use some sort of framework written on top of servlets to make development easier. E.G. if you suddenly have a use case for a request to return json then spring mvc already supports it whereas with servlets you'd have to figure it out yourself. It's still useful to know servlets as it's the underlying technology.
  • Roger
    Roger almost 11 years
    I see. So basically a servlet is created with both methods, doing the exact same thing - only that in #2 you use Spring MVC as the framework to help you on the way? That is, with the help of Spring MVC's @Controller, DispatcherServlet and some JSP ("java in html"), you create the same thing as if you would create a Servlet ("html in java"(ie. New -> Servlet...)) and some JSP/html on your own, only that in the Spring MVC case, Spring takes care of the "nasty parts" of the servlet business "for free"? Would that be a correct comprehension of it all? (Sorry for being a bit slow :)
  • Ben Thurley
    Ben Thurley almost 11 years
    Pretty much. You're right that in both cases you'll want a JSP to render the view. Typically the controller or servlet will call your services to get/set data, save it in the request and then forward onto a jsp. Spring MVC can help here too with it's view resolvers for finding the correct view.