Enterprise Integration Zone is brought to you in partnership with:

I'm a software architect with Lockheed Martin Mission Systems and Training. Most of my recent work has been with Java Enterprise, especially JBoss, but I've worked with C, C++, C#, Ada, Python, MATLAB, and a few other things over time. Alan is a DZone MVB and is not an employee of DZone and has posted 13 posts at DZone. You can read more from them at their website. View Full User Profile

Add REST to Standalone Java with Jetty and Spring WebMVC

  • submit to reddit

There are a lot of tutorials out there about providing REST web services in a servlet container by building and deploying a WAR. There are also cases where someone is looking to put a REST interface on an existing Java application. In that case it isn’t always possible to turn the application into a WAR or EAR and adding a servlet container as a separate process just adds a layer of complexity.

At the time, I didn’t see a good example that brought all the pieces together for a standalone Java application that exposes REST interfaces using Spring WebMVC. So I put together a small example. If I’d looked harder, I would have found one, but now I’ve written it and get to share it.

Even though the example is small, there are a number of moving parts, and I want to do them justice. So I’m going to start by discussing the Spring WebMVC configuration and move on from there in future posts.

One other thing I like about this example is that we can build up everything required to actually make a WAR, but then run it as a standalone Java application. I’ve always thought that to be one of the coolest things about Jenkins and I think it’s a useful technique in general.

To begin, in order to make a webapp, we’ll add a web.xml file. With Servlet 3.0 we could avoid having a web.xml, but it’s nice to have one as it keeps us compatible with Servlet 2.x. We’re using Maven, so it goes in src/main/webapp/WEB-INF.

<?xml version="1.0" encoding="ISO-8859-1"?>
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" 

  <display-name>REST API</display-name>
  <description>Sample Spring WebMVC REST API</description>




There’s not much to this configuration. The main thing to note is that we’re not implementing a servlet ourselves; we’re letting Spring WebMVC’s DispatcherServlet do the work. The DispatcherServlet does exactly what it sounds like: it takes in requests and figures out where they should go.

In the same WEB-INF directory we now need to configure Spring WebMVC. To do this we need a file called rest-servlet.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
  http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <context:component-scan base-package="org.anvard.webmvc.server"/>


The file name is important, as Spring WebMVC is going to look for a file with this name because of the <servlet-name> we provided in web.xml. It’s important to remember to change one if you change the other.

This is a regular Spring XML configuration file. We could create arbitrary beans here, link them together, configure transaction management, persistence, whatever we choose. In this case, we’re using two items that were added to Spring within the last few years and relate to Spring’s new annotation-driven configuration.

  • <context:component-scan> tells Spring that rather than listing all the beans in the XML file, we want it to scan the classpath. We give it a base-package to make the search more efficient and to make sure it doesn’t pick up things we don’t want. There are a number of Spring class-level annotations that will tell Spring that a class should be instantiated as a bean, but for WebMVC purposes we will use @Controller.
  • <mvc:annotation-driven/> tells Spring that as beans are added to the Spring application context, it should search them for WebMVC annotations in order to find targets for the dispatcher. More on this next time, but there’s also the excellent Spring reference documentation.

As the name implies, Spring WebMVC is about bringing the model-view-controller design pattern to web programming. Controllers handle requests, optionally pulling in data from the model. As much as possible, the Spring framework itself handles the view, which for REST interfaces mostly means converting to JSON or XML.

Our controller Java class looks like this:

package org.anvard.webmvc.server; 

 import org.anvard.webmvc.api.Calculation;
 import org.springframework.stereotype.Controller;
 import org.springframework.util.Assert;
 import org.springframework.web.bind.annotation.PathVariable;
 import org.springframework.web.bind.annotation.RequestBody;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestMethod;
 import org.springframework.web.bind.annotation.ResponseBody;
 public class Calculator {
     @RequestMapping(value = "/calc/{op}/{left}/{right}", 
                     method = RequestMethod.GET)
     public Calculation calculate(@PathVariable("op") String op, 
             @PathVariable("left") Integer left,
             @PathVariable("right") Integer right) {
         Calculation result = new Calculation();
         return doCalc(result);
     @RequestMapping(value = "/calc2", method = RequestMethod.POST)
     public Calculation calculate(@RequestBody Calculation calc) {
         return doCalc(calc);
     private Calculation doCalc(Calculation c) {
         String op = c.getOperation();
         int left = c.getLeft();
         int right = c.getRight();
         if (op.equalsIgnoreCase("subtract")) {
             c.setResult(left - right);
         } else if (op.equalsIgnoreCase("multiply")) {
             c.setResult(left * right);
         } else if (op.equalsIgnoreCase("divide")) {
             c.setResult(left / right);
         } else {
             c.setResult(left + right);
         return c;

Next time I’ll talk in detail about the various WebMVC annotations and how they’re used to expose different types of REST interfaces. For today, I want to finish with the point that this is a complete example of a Spring WebMVC REST application. We could build a WAR with these three files (and the Spring dependencies) and it would deploy to a servlet container and expose REST interfaces. With the right dependencies, this example will return XML or JSON to a client, depending on what the client requested.

Published at DZone with permission of Alan Hohn, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)


Juanfezero Juan... replied on Wed, 2013/10/09 - 8:49am

Thanks for the post. 

May you explain how to run the example?

Is Jetty dependent? I imagine that is it.

Jakub Milkiewicz replied on Wed, 2013/10/09 - 3:11pm in response to: Juanfezero Juanfezero Zerojuanfe

As jetty maven plugin is defined in pom it is just a matter of executing mvn jetty:run. 

Then point your browser to http://localhost:8080/rest/calc/add/2/2

Alan Hohn replied on Wed, 2013/10/09 - 5:02pm in response to: Jakub Milkiewicz

Yep, exactly, thanks. 

I've been lazy and been running it within Eclipse using Eclipse's Maven support, just running the main() in EmbeddedServer. I really ought to get Maven making an executable JAR that could be run anywhere - the idea is to be independent of jetty:run.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.