25

In my current company we are starting a new project that will be a REST API in Java, deployed in a servlet container like Tomcat. In my previous experience using REST frameworks like JAX-RS with Jersey, JBOSS REST Easy, Spring MVC I know what are some of the advantages of using a framework like those over writing directly the Servlets for processing the requests.

(Of course we know that the mentioned frameworks still use Servlets under the covers)

I am finding difficult to convince them. As they are proposing to write servlets thinking it is better for performance (which can be the case but I think the overhead of using one of those frameworks should be insignificant for a REST API).

Here are my reasons:

1) Less boilerplate and more concise code (which is easier to maintain and test). With a JAX-RS framework or SpringMVC you can define a REST resource very easily by writing methods with annotations indicating the PATH of the resource, the http method to use, query and url parameters, headers like encoding accepted, etc.

Example:

@GET
@Path("/users")
@Produces({MediaType.APPLICATION_JSON}) 
public UserList getUsers(@QueryParam("group") String group) {
    return userService.findUsers(group);
}

With servlets you will need at least something like this:

Map the url for each servlet in web.xml (Which is not necessary in and above Servlet 3.0):

<servlet>
    <servlet-name>UsersServlet</servlet-name>
    <servlet-class>test.UsersServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>UsersServlet</servlet-name>
    <url-pattern>/users</url-pattern>
</servlet-mapping>

Then inside the servlet class:

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    String group = request.getParameter("group");
    response.setContentType("application/json");
    PrintWriter out = response.getWriter();
    JsonSerializer someJsonSerializer = new JsonSerializer();
    String json = someJsonSerializer.serialize(userService.findUsers(group));      
    out.print(json);
}

2) Adaptability. The mentioned frameworks allow you to easily add features to your application that otherwise you will need to do it manually, like using multiple media type inputs and outputs. For example making a service to return xml or json or any other depending on the accept header. Frameworks like SpringMVC and Jersey make it very easy to configure serializers/deserializers for your requests, responses.

3) REST best practices. Normally those frameworks are built over a solid understanding of the best practices to be followed by a REST API and are defined based on standards of the REST architecture which makes easier to build a solid and standard conforming application. In the other hand Servlets give you a so high level of freedom on how to process your requests/responses that it will be more difficult to realize that you are not being RESTfull at all.

Any other?

10
  • 2
    Performance may sound like a rational reason, but I think there is an emotional reason at play here, e.g. "Not Invented Here" or "Afraid of the Unknown" (big bad frameworks). No number of rational reasons for a framework will change this (even if it is counter productive).
    – vanOekel
    Feb 21, 2014 at 23:59
  • 1
    Can't you use both? Direct servlets for the complicated stuff and the framework for fluffy media stuff? Feb 22, 2014 at 0:01
  • 4
    Quit that company! neither you, nor the company are going to be satisfied with each other, if you really need to try so HARD to persuade some "architects" to use those standard and almost outdated frameworks.
    – injecteer
    Feb 22, 2014 at 0:23
  • 4
    I totally agree with your colleagues. I spent 7 years using frameworks for all the reasons you invoked and I am now spending 2 years returning to plain Serlvet + HTML + js stuff. Less to learn, to debug and far more better performances. And I your code is a bit vebose, you can factorise it in serveral methods that will be far more easier to write than another framework to learn. With servlet 3.0 the utility of theses is less obvious.
    – Orden
    Feb 9, 2016 at 19:10
  • 2
    Thanks to Servlet 3.0 you don't need to do this in web.xml anymore, you declare this in each servlet class with WebServlet and WebFilter annotations. I did it recently and it's easier to do than to set-up Jersey.
    – Orden
    Feb 22, 2016 at 16:57

4 Answers 4

31

Let me play the devil's advocate with my answer.

First, you don't need to add the servlets to the web.xml file. Servlets 3.0 allow you to use annotations.

Second, there really is a significant performance hit with these frameworks. See these benchmarks

Third, you can use GSON within a servlet, which is faster than Jackson (used by default in Spring and Jersey). This gets you even more performance especially considering that performance is critical to your requirements.

Finally, if you are concerned about boilerplate, put that code that you wrote inside the servlet in some utility class and use it from multiple servlets. That beats carrying around a framework's huge load when you (like most people) would probably be using a small fraction of its functionality.

5
  • 3
    And then I can write my own annotations and annotate my utility methods, finally I will have my own Jersey
    – raspacorp
    Aug 12, 2014 at 0:38
  • 3
    In what benchmark is GSON faster than Jackson @stepanian, this one says the opposite: rick-hightower.blogspot.com/2014/04/…
    – raspacorp
    Aug 12, 2014 at 0:43
  • 1
    @raspacorp You don't need to write your own annotations - servlets already support annotations for paths in lieu of web.xml. You shouldn't write your own Jersey. The whole point is avoiding the overhead of a large framework when you are only using it to serve JSON from REST endpoints. If you are using all the other features that Jersey provides, then, by all means, use it. Then the overhead would be justified.
    – stepanian
    Aug 12, 2014 at 5:07
  • 1
    @raspacorp If you believe that benchmark and think that Jackson is faster, then use Jackson. The beauty of not being tied to a framework is that you can pick what to use. (Technically, you can use GSON with Jersey and Spring, but it is a big pain in the neck, just like any other minor modification you need to make to the rigid way a framework operates).
    – stepanian
    Aug 12, 2014 at 5:12
  • @stepanian, I'm having a hard time finding an answer as to what features Jersey is really providing on top of Servlets. Being in a similar "which to use" boat myself, any pointers or info to what Jersey, etc. provide on top of Servlets would be a huge help!
    – cdeszaq
    Feb 2, 2017 at 15:09
7

Several months ago I put a comment saying that I did support for the pure Servlet 3.0 solution against the use of REST MVC frameworks.

After months of usage, I confirm my choice!

I tried to install Jackson and others frameworks but it needs more work than writing the extra 5 lines of code and I don't have to cope with an extra software component to setup, learn, update...

Here is my working example:

package example;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;

/**@WebServlet(name = "booking", urlPatterns = { "/api/v1/booking" })*/
public class BookingWs extends javax.servlet.http.HttpServlet {

    public static final Logger LOGGER = LoggerFactory.getLogger(BookingWs.class);

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        try {
            // Used for JSON handling
            Gson gson = new Gson(); 
            
            // De-serialize from request
            BookingRequest bRequest = gson.fromJson(request.getReader(), BookingRequest.class);
            
            // Do your business logic.
            BookingResponse bResponse = new BookingResponse();
            bResponse.request = bRequest;
            bResponse.accepted = "bar".equalsIgnoreCase(bRequest.type);
            bResponse.reason = bResponse.accepted ? "Welcome" : "Only bar table booking left";
            
            // Serialize and send response back;
            response.setContentType("application/json");
            PrintWriter pw = response.getWriter();
            gson.toJson(bResponse, pw);
        } catch (Throwable t) {
            response.setStatus(500);
            PrintWriter pw = response.getWriter();
            pw.write("{\"error\":\"" + t.getLocalizedMessage() + "\"}");
        }
    }
}

class BookingRequest{
    String type;
    int seats;
    String name;
    long requiredTimestamp;
}

class BookingResponse{
    BookingRequest request;
    boolean accepted;
    String reason;
}  

Maybe these frameworks have a feature you need absolutely, but for me it should be decisive enough to worth the hassle of extra libs.

As a French author Antoine de Saint Exupery said:

"Perfection is Achieved Not When There Is Nothing More to Add, But When There Is Nothing Left to Take Away".

I took away Jackson to get closer to it :-)

(Yes I have to admit, I used GSON, but it's a small jar, without any configuration needed).

3
  • 1
    I agree, for small things writing a servlet is easier and maybe more performant, but when writing a REST API where you're going to publish many resources, media types and you need to leverage security, asynchronous services, etc. I would definitely go for a full stack framework like Spring or some that can be easily plugged to other enterprise app dev frameworks, e.g. Jersey. By the way if you are using Jersey or SpringMVC you don't need to configure Jackson but just add the dependency to your project by using Maven for example, json and xml serializing frameworks are supported out of the box.
    – raspacorp
    Sep 26, 2016 at 16:52
  • 1
    I love the quote - I will definitely use it! To make the code even terser, you can move the PrintWriter instantiation outside the try/catch block. This may please those who count lines (but have no problem slowing down their application by adding vast amounts of unused framework code).
    – stepanian
    Oct 9, 2016 at 19:49
  • I use it for a REST API for a model of 100 tables and many ressources and it has been working fine for 2 years now and with no security problems neither. As a consultant for big entreprises during 18 years, I have been quite sucessfull solving stability and performance issue by getting rid of "enterprise full stacks" ;-)
    – Orden
    Jul 16, 2018 at 21:40
4

First, I would consider setting up a simple test with two applications which have a "Hello World" servlet -- one with pure servlets, one with Spring MVC or Apache CXF or your framework of choice. Then run a performance test to prove (hopefully) that the performance hit is insignificant.

Also, serializers and deserializers are one good example, but the interceptor/filter pattern that is available in these frameworks is very useful for other things as well:

  • Authentication/Security
  • Logging of raw requests if needed
  • Header and content transformations that can be kept separate from business logic

In addition, there are tools that plug into these frameworks that will generate documentation (WADLs/WSDLs/Enunciate) and client class libraries. There are also testing libraries that can be used to generate automated tests against well known frameworks.

I used to reinvent the wheel too. But it no longer makes sense (if it ever did.)

0

For me the real advantage of using Spring MVC is the increase of productivity. Writing everything from scratch to tune things up make sense if you need a really customized application. Although it can be cool to create something new with no frameworks at all, when it gets bigger, you will face problems that were already solved by hundreds of damn good developers. Using Spring MVC will save you a lot of time that you would probably waste reinventing the wheel and even more time when you will have to train someone to deal with your awesome custom code.

1
  • Sorry, but I took theses reasons 18 years ago (I started coding in 1985. They make us bought Hibernate, EJB, JavaBeans, JSF. Backed up by big names and a lot of excellent developers. Too many cooks spoiled the plate and I now prefer my own lighter wheel.
    – Orden
    Aug 12, 2018 at 18:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.