Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Spring + REST + JSON = SOAUI

1. Introduction

In this tutorial we will see an example of how to do with Spring REST services where the input and output parameters will be JSON objects.

REST or RESTful ( REpresentational State Transfer ) is a type of web services that are not based on the SOAP standard. One of its main advantages is that they are much lighter since they require many less headers and layers (usually a simple GET or POST).

JSON ( JavaScript Object Notation ) is a lightweight information exchange format (much lighter than XML) that is based on key-value pairs.

The idea is to use these technologies to build what we will call SOAUI , that is, a service layer (SOA = Service Oriented Architecture) on which we will assemble the user interface (UI = User Interface). With this architecture we can completely uncouple the presentation of the business, so that the interface could be developed in HTML + JavaScript, or in Flex, or in iPhone, or in Android, or to communicate with another process, or …

The advantages of this architecture are clear, and in this tutorial we will see how with Spring it will be extremely easy to assemble this architecture.

find all the source code with Maven (compiled withmvn installfrom the project “tutorial-parent”), and configured with HSQLDB  and Jetty (run with mvn jetty:runfrom the project “tutorial-rest”).

Once raised the Jetty you can enter the application with a browser and the URL:
http: // localhost: 8080 / autentia-rest-tutorial / rest / provider /

Other URLs that you can try:

  • http: // localhost: 8080 / autentia-rest-tutorial / rest / provider / 1: The last number is the id of the provider you want to show.
  • http: // localhost: 8080 / autentia-rest-tutorial / rest / provider / names: Returns a list with the names of the providers.

2. Environment

The tutorial is written using the following environment:

  • Hardware: Portable MacBook Pro 17 ‘(2.93 GHz Intel Core 2 Duo, 4GB DDR3 SDRAM, 128GB Solid State Drive).
  • NVIDIA GeForce 9400M + 9600M GT with 512MB
  • Operating System: Mac OS X Snow Leopard 10.6.4
  • JDK 1.6.0_20
  • Maven 2.2.1
  • Spring 3.0.4.RELEASE

3. Configuration

In the pom we have put the necessary dependencies to use the jar of Spring (core, web, …).

In the web.xml we can highlight the following:

...
contextparam>
    paramname>contextConfigLocation/paramname>
    paramvalue>classpath*:applicationContext.xml/paramvalue>
/contextparam>
listener>
    listenerclass>org.springframework.web.context.ContextLoaderListener/listenerclass>
/listener>
...
servlet>
    servletname>tutorial/servletname>
    servletclass>org.springframework.web.servlet.DispatcherServlet/servletclass>
    loadonstartup>1/loadonstartup>
/servlet>
servletmapping>
    servletname>tutorial/servletname>
    urlpattern>/rest/*/urlpattern>
/servletmapping>
...    

It would be the typical configuration of Spring Web, where we see how the listener that loads the fileapplicationContext.xml is declared and how the Spring Dispatch Servlet is declared that will attend all the requests that start withrest. We gave this servlet
the tutorial name , so Spring will look for a tutorial-servlet.xml configuration file where we will put the web layer configuration.

In the tutorial-servlet.xml we can find:

...
mvc:annotationdriven />
context:componentscan basepackage=“com.autentia.tutorial.web” />
bean class=“org.springframework.web.servlet.view.ContentNegotiatingViewResolver”>
    property name=“mediaTypes”>
        map>
            entry key=“html” value=“text/html” />
            entry key=“json” value=“application/json” />
        /map>
    /property>
    property name=“viewResolvers”>
        list>
            bean class=“org.springframework.web.servlet.view.InternalResourceViewResolver”>
                property name=“prefix” value=“/WEB-INF/views/” />
                property name=“suffix” value=“.jsp” />
            /bean>
        /list>
    /property>
    property name=“defaultViews”>
        list>
            bean class=“org.springframework.web.servlet.view.json.MappingJacksonJsonView” />
        /list>
    /property>
/bean>
...

We see how it is indicated that we will use the configuration by annotations and that you should look for these annotations from the package  com.autentia.tutorial.web .

Then a bean of type ContentNegotiationgViewResolver is defined . This is a Spring resolve that what it does is, depending on the headers of the request or the extension that we put in the URL determines which type of view is the one that has to “paint” the result. At this point it is important to highlight how in the  defaultViews we are indicating that the default view is the  MappingJacksonJsonView . This class will be responsible for transforming JSON’s responses to our methods.

In the applicationContext.xml there is nothing special, just the definition of the datasource, the transactionalmanager, and the business beans.

4. The controller

This is where all the chicha is, if it can be called “chicha” because you will see how it is extremely simple.

@Controller
@RequestMapping(“/provider”)
public class ProviderController {
    private final ProviderStore providerStore;
    @Inject
    public ProviderController(ProviderStore providerStore) {
        this.providerStore = providerStore;
    }
    @RequestMapping(method=RequestMethod.GET)
    public String getCreateForm(Model model) {
        model.addAttribute(new Provider());
        return “provider/createForm”;
    }
    @RequestMapping(value=“/names”, method=RequestMethod.GET)
    public @ResponseBody ListString> getProvidersNames() {
        return providerStore.getProvidersNames();
    }
    @RequestMapping(value=“/store”, method=RequestMethod.POST)
    public @ResponseBody Long addProvider(@RequestBody Provider provider) {
        final Provider storedProvider = providerStore.sotreProvider(provider);
        return storedProvider.getId();
    }  
    @RequestMapping(value=“/{id}”, method=RequestMethod.GET)
    public @ResponseBody Provider getProvider(@PathVariable Long id) {
        final Provider provider = providerStore.loadProvider(id);
        if (provider == null) {
            throw new ResourceNotFoundException(id);
        }
        return provider;
    }
}

We can see how the class is declared as a@ControllerSpring. And with the annotation@RequestMappingof line 02 we are telling you that all the URLs that begin with the pattern/providerwill be taken care of by this class (to see some examples, look at the URLs that appear in the introduction of this tutorial).

Then we have a series of methods where we are fine-tuning the behavior of the controller.

On line 18 we see how we use the annotation again @RequestMapping, but this time we indicate by usingvaluesthe URL pattern that will be served by this method (/provider/names). And withmethodwe indicate that this method will only address the requests made by GET.

In the following line we use@ResponseBodyto indicate that the result of the method overturns it in the body of the answer. As we have configured that the default view is the JSON transformation, what will happen is that Spring will take our result, it will represent it in JSON and will write it in the body of the response.

The annotation appears on line 24@RequestBody. With this we are indicating to Spring that the body of the request is passed to us as a parameter of the method. Spring will take care of converting the JSON object into an instance ofProvider(the Provider class is a normal POJO, Spring will do the conversion by introspection).

In line 29 and 30 we can highlight the use of{id} and the annotation@PathVariable. With this we are indicating that a part of the URL must be interpreted as a
variable, which Spring will inject us as a parameter of our method.

On line 33 we are throwing an exception:

@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
    private static final long serialVersionUID = 4553464302467525828L;
    private Long resourceId;
    public ResourceNotFoundException(Long resourceId) {
        this.resourceId = resourceId;
    }
    public Long getResourceId() {
        return resourceId;
    }
}

In the code of this exception, on line 1 we see how, thanks to the annotation,@ResponseStatuswe are indicating to Spring that when this exception is issued, the client is sent a 404 code of resource not found.

5. The view

The view is pure HTML + JavaScript. JSPs with Spring taglibs have been used, but simply for convenience when generating the form.

In the JSP createForm.jsp you can see how JavaScript ( jQuery ) is used to make the
call by AJAX and send a JSON object in the request.

@ page session=“false” %>
@ taglib uri=“http://java.sun.com/jsp/jstl/core” prefix=“c” %>
@ taglib uri=“http://java.sun.com/jsp/jstl/fmt” prefix=“fmt” %>
@ taglib prefix=“form” uri=“http://www.springframework.org/tags/form” %>
html>
    head>
        title>Create Provider/title>
        =“text/javascript” src=/scripts/jquery1.4.min.js” /> “>
        =“text/javascript” src=/scripts/json.min.js” /> “>
    /head>
    body>
        div class=“container”>
            h1>
                Create Account
            /h1>
            div class=“span-12 last”>    
                form:form modelAttribute=“provider” action=“provider/store” method=“post”>
                    fieldset>        
                        legend>Provider Fields/legend>
                        p>
                            form:label for=“name” path=“name” cssErrorClass=“error”>Name/form:label>br/>
                            form:input path=“name” />form:errors path=“name” />
                        /p>
                        p>  
                            input id=“create” type=“submit” value=“Create” />
                        /p>
                    /fieldset>
                /form:form>
            /div>
        /div>
        div id=“mask” style=“display: none;”>/div>
        div id=“popup” style=“display: none;”>
            div class=“span-8 last”>
                h3>Account Created Successfully/h3>
                form>
                    fieldset>
                        p>
                            label for=“assignedId”>Assigned Id/label>br/>
                            input id=“assignedId” type=“text” readonly=“readonly” />    
                        /p>
                        p>
                            label for=“confirmedName”>Name/label>br/>
                            input id=“confirmedName” type=“text” readonly=“readonly” />
                        /p>
                    /fieldset>
                /form>
                a href=“#” onclick=“closePopup();”>Close/a>          
            /div>            
        /div>        
    /body>
    =“text/javascript”>  
        $(document).ready(function() {
            $(“#provider”).submit(function() {
                var account = $(this).serializeObject();
                $.postJSON(“provider/store”, account, function(data) {
                    $(“#assignedId”).val(data);
                    showPopup();
                });
                return false;              
            });
        });


This post first appeared on Targetveb, please read the originial post: here

Share the post

Spring + REST + JSON = SOAUI

×

Subscribe to Targetveb

Get updates delivered right to your inbox!

Thank you for your subscription

×