2010-01-30

REST with Spring 3.0, Spring MVC and Dojo. Part 1 - GET

Introduction


I am going to write a few posts on RESTful application development with Spring 3.0, using Spring MVC, Dojo and Maven. In the first part, I will show you how to create a basic controller and handle a GET request. The rest: DELETE, POST, PUT we will cover later.

I would suggest that - in case you're not very familiar with REST - you read some information about REST, for instance A Brief Introduction to REST from InfoQ or this article on REST conventions.

I am going to use a Maven project in Eclipse Ganymede with the M2Eclipse plugin, the latest development build (0.9.9.200912160759), as the latest production release contains some weird bugs including this annoying bug that seems to be fixed in the development build (it's time to release, guys!).

I am also going to use JBoss 5.1.0 JDK6 and that's why I will put one of the Spring beans files (applicationContext.xml) in the classes folder of the output war which is ugly but it works (it didn't work when I put it in /WEB-INF/; it did work in WebSphere though). Funny that when I called it beans.xml I would actually get an exception from JBoss: javax.inject.DefinitionException: bean not a Java type. Handy, I guess we're getting somewhere with error reporting.

One more thing, I am using Java 1.6 but Java 1.5 will suffice for everything - except for validation where a Java 6 annotation will be used. It is possible to implement your own validation though, it's really up to you. Validation will be shown in the POST and PUT parts. In this post only very basic (type) validation will be shown.

What you will learn


Let us begin! We are going to handle GET requests - in this example two GET requests. One without parameters (it will return all books - books will be sample items in this example) and one with a parameter - book ID. This will allow you to see:

  • How to handle input RESTful parameters with Spring MVC
  • How to return a collection of items
  • How to return a single item

Operation REST method Sample URI
Return item(s) GET /books (all books)
/books/ (all books)
/books/12 (one book with ID = 12)
Create a new item POST (you pass the ID in the object itself)
/books
/books/
Update an item PUT (you pass the ID in the object itself)
/books
/books/
Delete an item DELETE /books/12 (book with ID = 12)

The controller


Let's take a look at our controller class - the controller will handle the requests.

package me.m1key.restsample.controllers;

import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
// Some imports excluded for brevity, eh?

/**
 * Books controller.
 *
 * @author Michal Huniewicz
 *
 */
@Controller
@RequestMapping("/books")
public class SampleController {
    // Methods excluded for brevity.
}

This is it, it doesn't have to implement or extend anything. It is only annotated as a controller with the @Controller annotation. It means it can have many actions, like MultiActionController in the old days.

It is also annotated with @RequestMapping. This is where we specify the path which this controlller is to handle. As you will see, the action methods will also be annotated with this to further narrow down the criteria.

Setup


Now, how will Spring know about this Controller? We will tell it specifying certain information, first in the web.xml file.

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    <display-name>Books REST Handler</display-name>

    <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>rest.root</param-value>
    </context-param>

    <!-- Servlets -->

    <servlet>
        <servlet-name>rest</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>rest</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
    
    <!-- Rest of the file omitted for brevity. -->

</web-app>

In the web.xml file we declare the dispatcher servlet from Spring and we ask the server to load it on startup. We also assign this servlet to a certain path, that is /rest/* preceded by application's context root.

Now, because we specified the servlet name to be rest, we will create one more file next to web.xml (in the /WEB-INF/ folder that is) called rest-servlet.xml. While web.xml is a standard JEE file, this rest-servlet.xml file is a Spring Framework kind of file.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:oxm="http://www.springframework.org/schema/oxm"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
                http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd">

    <context:component-scan base-package="me.m1key.restsample.controllers" />
    
    <!-- Rest of the file omitted for brevity. -->



And this is how we tell Spring to search for components: with the context:component-scan element that specifies where to look for components in our application. An alternative would be to declare all the beans separately with the bean element.

Controller actions - return all books


What we did so far is we declared a controller, we told the server and Spring about it. It's time to write some actions.

package me.m1key.restsample.controllers;

import java.util.List;

import me.m1key.restsample.Factory;
import me.m1key.restsample.beans.BooksBean;
import me.m1key.restsample.to.BookTO;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

/**
 * Books controller.
 *
 * @author Michal Huniewicz
 *
 */
@Controller
@RequestMapping("/books")
public class SampleController {

    private static final String BOOKS = "books";

    /**
     * Returns all books.
     *
     * @return all books
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    public ModelAndView handleAllBooks() {
        ModelAndView mav = new ModelAndView();

        BooksBean booksBean = Factory.getBooksBean();

        List booksTO = booksBean.loadBooks();

        mav.addObject(BOOKS, booksTO);

        return mav;
    }

    // Rest of the code omitted for brevity.

}

Please take a look at the handleAllBooks method. It is annotated with @RequestMapping, like promised. That means that it will handle /books/ (or /books without the trailing backslash slash backslash slash) requests (within the app context root). What it returns is a ModelAndView object, that's it. We use BooksBean to get us the list of all books as controllers shouldn't really contain that kind of logic (see the MVC pattern). In our example BooksBean is just a dummy object, so it doesn't use any data source like it would in a real application.

There are two more things I must mention.

  • You should not call ModelAndView#addObject() more than once because if you do you might get inconsistent results depending on the output format (JSON/XML/...). To be precise, with JSON you would get all the objects no matter how many times you call addObject. With XML - just one. It looks like a bug but Arjen Poutsma was kind enough to explain to me that it isn't.
  • Wait a second, I'm talking JSON, XML, but the code just returns a ModelAndView object... That's right, the Controller is not aware of the output method. Ideally, we should be able to say /rest/books.json and get JSON response, /rest/books.xml and get XML response, /rest/books.html and get HTML response, /rest/books.mp3 and get a bunch of ladies singing the book titles. In this simple application we are going to handle only JSON and XML.

Telling Spring about the output methods we support - XML and JSON


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:oxm="http://www.springframework.org/schema/oxm"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
                http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd">

    <context:component-scan base-package="me.m1key.restsample.controllers" />

    <bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <bean id="mappingJacksonHttpMessageConverter"
                    class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
            </list>
        </property>
    </bean>
    <bean
        class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <property name="mediaTypes">
            <map>
                <entry key="json" value="application/json" />
                <entry key="xml" value="application/xml" />
            </map>
        </property>
        <property name="defaultViews">
            <list>
                <bean
                    class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
                <bean class="org.springframework.web.servlet.view.xml.MarshallingView">
                    <constructor-arg>
                        <bean class="org.springframework.oxm.xstream.XStreamMarshaller"
                            p:autodetectAnnotations="false" />
                    </constructor-arg>
                </bean>

            </list>
        </property>
        <property name="defaultContentType" ref="jsonMediaType" />
        <property name="ignoreAcceptHeader" value="false" />
    </bean>

    <bean id="jsonMediaType" class="org.springframework.http.MediaType">
        <constructor-arg value="application/json" />
    </bean>

</beans>

Update 2010-03-31: Ralph Engelmann reported that the last bean definition is not valid as of Spring 3.0.1.RELEASE (see comments below). If you are using this version of later, you must define this bean in the following manner:
<bean id="jsonMediaType" class="org.springframework.http.MediaType">
    <constructor-arg value="application"/>
    <constructor-arg value="json"/>
</bean>
Thanks goes to Ralph.

Whew!

The first part (with AnnotationMethodHandlerAdapter) tells Spring which input methods we support (it will be useful when we send objects to the server via REST).

The second part (with ContentNegotiatingViewResolver) tells Spring which output methods we support (in this example, JSON and XML, as you can see).

Below we also define the default (preferred by us) output format. Please note that the client can still ignore it and request another one if available.

Controller actions - return one book by ID


This is going to be a bit more interesting than returning all the books for two reasons:
  • We must handle an entry parameter via REST (the requested book ID).
  • We must handle the situation when the requested book cannot be found.

Let's see the action method.

/**
     * Returns a single book by ID.
     *
     * @param response
     *            response
     * @param bookId
     *            book ID
     * @return single book
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public ModelAndView handleBookById(HttpServletResponse response,
            @PathVariable("id") Long bookId) {
        ModelAndView mav = new ModelAndView();

        BooksBean booksBean = Factory.getBooksBean();

        BookTO bookTO = booksBean.loadBookById(bookId);

        mav.addObject(BOOK, bookTO);

        return mav;
    }

Now, with the new RequestMapping annotation we narrow down the query criteria. This mapping will handle /rest/books/1 kind of addresses (preceded by context root). Please note the @PathVariable annotation that binds the variable in the request mapping to the annotated variable.

See the response parameter? It's not used at the moment. Luckily, it doesn't break the method. For now, it would work (handle requests that is) with or without the parameter. We will use it later.

Hm, how does basic parameter validation work? What if I say /rest/books/x? Well, x is not a Long, so I will get a 404 - nice.

But if the book doesn't exist - that's a different story. In my dummy BooksBean I only have two books, so if I say /rest/books/3 the bean method returns an empty object. Not nice. When the book doesn't exist - we want to return a 404. This is why we need the response object. Let's look at the improved action method.

/**
     * Returns a single book by ID.
     *
     * @param response
     *            response
     * @param bookId
     *            book ID
     * @return single book
     * @throws IOException
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public ModelAndView handleBookById(HttpServletResponse response,
            @PathVariable("id") Long bookId) throws IOException {
        ModelAndView mav = new ModelAndView();

        BooksBean booksBean = Factory.getBooksBean();

        BookTO bookTO = booksBean.loadBookById(bookId);

        if (bookTO.getId() == null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "Book "
                    + bookId + " not found.");
        }
        mav.addObject(BOOK, bookTO);

        return mav;
    }

If we detect that the returned book is empty - we write to response a 404 error (SC_NOT_FOUND).

Results


That's quite a post. Let us look at the output XML and JSON.

All books in XML:

<list>
    <me.m1key.restsample.to.BookTO>
        <id>1</id>
        <name>Lord of the Rings</name>
    </me.m1key.restsample.to.BookTO>

    <me.m1key.restsample.to.BookTO>
        <id>2</id>
        <name>My Name Is Red</name>
    </me.m1key.restsample.to.BookTO>
</list>

All books in JSON (I broke it into 3 lines myself for readability):

{"books":
    [{"name":"Lord of the Rings","id":1},
    {"name":"My Name Is Red","id":2}]}

One book in XML:

<me.m1key.restsample.to.BookTO>
    <id>1</id>
    <name>Lord of the Rings</name>
</me.m1key.restsample.to.BookTO>

One book in JSON:

{"book":{"name":"Lord of the Rings","id":1}}


That's it for now. In the next post I will show you how to access this data with Dojo.

Download source code for this article

  1. REST with Spring 3.0, Spring MVC and Dojo. Part 1 - GET
  2. REST with Spring 3.0, Spring MVC and Dojo. Part 2 - GET from Dojo perspective
  3. REST with Spring 3.0, Spring MVC and Dojo. Part 3 - POST and JSR-303 validation
  4. REST with Spring 3.0, Spring MVC and Dojo. Part 4 - PUT (updating objects)
  5. REST with Spring 3.0, Spring MVC and Dojo. Part 5 - DELETE

21 comments:

  1. Hello, your Post helped my a lot. But your "jsonMediaType" Bean did not work for me (Spring 3.0.1.RELEASE), i get an IllegalArgumentException: Invalid token character '/' in token "application/json". I have changed it to:

    so it works for me.

    Best Regards

    ReplyDelete
  2. Sorry: i have some troulbe with the xml: I changed the "jsonMediaType" bean configuration to use the 2 parameter constructor:

    first parameter (index="0") value="application",

    second parameter (index="1") value="json"

    ReplyDelete
  3. Hey Ralph, thanks for your comment.

    I just checked my project and "application/json" works without any problems - however my org.springframework.http.MediaType bean is Spring 3.0.0.RELEASE so that might be the reason.

    I will download the source for 3.0.1.RELEASE and compare it to 3.0.0.RELEASE and let you know if I find anything out.

    ReplyDelete
  4. OK, found it!

    This, indeed, is a change in 3.0.1, that's why I didn't have this problem.

    Thanks for pointing it out and here you can find a little bit of explanation by Arjen Poutsma (post #3):
    http://forum.springsource.org/showthread.php?t=85004

    Best regards.

    ReplyDelete
  5. This may seem like a dumb question, but... the XML version of the returned bean is fairly ghastly compared to the JSON, i.e.

    <me.m1key.restsample.to.BookTO>
    <id>1</id>
    <name>Lord of the Rings</name>
    </me.m1key.restsample.to.BookTO>

    compared to

    {"book":{"name":"Lord of the Rings","id":1}}

    Is there any simple way to get the XML to look like this?:

    <book>
    <id>1</id>
    <name>Lord of the Rings</name>
    </book>

    The clients I want to use this output don't really give a damn what Java wants to call the bean!

    ReplyDelete
  6. Nello, perhaps this could be of some help:






    org.springframework.oxm.xstream.Flight



    ...



    (http://docs.huihoo.com/spring/spring-web-services/1.0/oxm.html)

    ReplyDelete
  7. Uh oh. It lost my XML.

    [bean id="xstreamMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller"]
    [property name="aliases"]
    [props]
    [prop key="Flight">org.springframework.oxm.xstream.Flight[/prop]
    [/props]
    [/property]
    [/bean]

    ReplyDelete
  8. Thanks for that!

    I did find a reference to the XStreamMarshaller alias stuff eventually after my post above, but it doesn't fly under GAE. I have moved to using Castor ( http://www.castor.org ), which is a bit more complex to configure but works for me.

    ReplyDelete
  9. Nello,

    I'm happy to hear that. Thanks for visiting. :)

    ReplyDelete
  10. Mój problem polega na tym, że skonfigurowałem wszystko jak na obrazku, a mimo to w odpowiedzi kontener szuka mi jsp, a nie jsona. Masz na to jakąś radę?

    ReplyDelete
  11. [PL] Moim zdaniem to problem z view resolverem. Czy Twoj plik XML ma poprawna nazwe (nazwa servletu + "-servlet.xml")?
    Daj znac. :)

    [EN] Problem: Spring tries to find JSP instead of JSON.
    My Idea: It's a problem with the view resolver or your servlet.xml file has an incorrect name (servlet name + "-servlet.xml").

    ReplyDelete
  12. Thank you very much for this article! It helped me a lot.

    ReplyDelete
  13. Thank you, very good article. i am a bit stuck with the json i am receiving and adding that list to existing select box, can you help?

    ReplyDelete
  14. Hi there, what is wrong with your JSON response?

    ReplyDelete
  15. Hi, Mike - This example doesn't work for me. I created a war file from the sample given by you, but its giving me a 404 error on browser. Please help.
    - Rahul

    ReplyDelete
  16. I am using this url - http://localhost:8080/rest/books/1 as the servlet name is rest in web.xml. Let me know if i am making any mistake or else i can provide you the war file that i created. I'm publishing this on tomcat 6

    ReplyDelete
  17. Hi Rahul, I think you need to provide the war name in the URL as well. So, for a war file called rahul.war - http://localhost:8080/rahul/rest/books/1

    ReplyDelete
  18. Hi,

    First thanks for this post. But still i am having some question. I have created the controller and bean class and used DOJO to submit and fetch the data from server. But i was not able to do that but after changing the dojo code with your it is working as expected please review my dojo code and let me know what i am doing wrong.
    My Dojo Code (Not working)

    function sendForm() {
    var myForm = dijit.byId("myFormTwo");
    content: dojo.toJson(myForm.attr("value")),
    dojo.xhrPost({

    // The URL of the request
    url: "http://localhost:8080/DOJO_AJAX/updateContact.do",
    //content: dojo.formToJson(myFormTwo),
    //content: {"id":"1","name":"viveka gautam","mobile":"0067392109"},
    headers: { "Content-Type": "application/json"},
    content: dojo.toJson(myForm.attr("value")),

    //form: dojo.byId("myFormTwo"),
    // Handle the result as JSON data
    handleAs: "json",
    // The success handler
    load: function(jsonData) {
    var content = "";
    },
    // The error handler
    error: function() {
    }
    });
    }
    ###################

    Dojo code working(as taken from your example)

    function saveBook() {
    var newBook = {
    "id":1,"name":"name1"
    };
    var myForm = dijit.byId("myFormTwo");
    //content: dojo.toJson(myForm.attr("value")),
    var actualContent = dojo.toJson(myForm.attr("value"));
    //var actualContent = dojo.toJson(newBook);
    debugger;
    //Save.
    var deferred = this._request("rawXhrPost", {
    url: "http://localhost:8080/DOJO_AJAX/updateContact.do",
    handleAs: "json",
    postData: actualContent,
    headers: { "Content-Type": "application/json"}
    });
    deferred.addCallback(this, function(value) {
    alert("Retrieved " + value.name);
    });
    deferred.addErrback(this, function(value) {
    alert("Error: " + value);
    });
    }

    Please let me know what is wrong with the first code. after changing this code only everything is working find so there seeme to be some problem with my dojo code.

    Thanks

    ReplyDelete
  19. Gautam, I would provide an actual error handler to see what's wrong. Yours is empty.

    ReplyDelete
  20. I have exactly same configuration as above and I am testing using firefox-RESTClient and with that .json works fine however when i pass application/xml ,i receive json response.

    ReplyDelete
  21. Good tutorial.
    But please can you tell me what modifications I would have to do if I had to pull the data from database instead of using XML file (say I want to use spring jpa for example).
    Thanks.
    Kwame.

    ReplyDelete