Thursday, October 7, 2010

Spring 3 REST Web Services - json, xml and html

Recently I was trying to get a simple web service up and running with Spring 3. I wanted to be able to return either json, xml or html representations of the data. In order to do that I had to visit several sites and review bits and pieces of documentation. I now have something viable so I figured I would share it with others in hopes it would save them some time.

The following examples are going off of the tutorial posted here. You can download the source from the link above and update the Spring configuration based on the following. NOTE: The package names I am using are different from the original example.

Spring Configuration w/out Tiles

The following configuration assumes that you have the project setup from the URL provided above and that you have adapted the package names.

Here is how my Spring configuration file ended up looking after all my changes:



 
 
 
 
 
  
   
    gov.usda.plants.model.Employee
    gov.usda.plants.model.EmployeeList
   
  
 
 
  
 
  
   
    
    
    
   
  
  
   
    
    
     
     
     
    
   
  
  
   
    
     
    
   
  
 
 
 
  
 

Spring Configuration with Tiles The following assumes you have the WEB-INF/layouts and WEB-INF/views directories and that you have copied the employees.jsp page from the WEB-INF/jsp folder to the WEB-INF/views folder. You will also need the following files configured for tiles:
WEB-INF/views/views.xml



 

 
  
  
 



WEB-INF/layouts/layouts.xml



 
 
 
 



WEB-INF/layouts/main_template.jsp (tiles template) I won't provide content for this since it's just a template JSP page, which can be anything you want it to be.


 
 
 
 
 
  
   
    gov.usda.plants.model.Employee
    gov.usda.plants.model.EmployeeList
   
  
 
 
  
 
  
 
   
    
    
    
   
  
  
   
    
    
    
     
     
     
    
   
  
  
   
    
     
    
   
  
 
 
 
 
  
  
 
 
 
 
 
 
   
     
       /WEB-INF/layouts/layouts.xml
       /WEB-INF/views/views.xml
     
   
 
 
 
 
  
 

Testing the Application
To test the application I used the "Simple Rest Client" extension in Google Chrome. It allows you to change the header values so you can ask for different representations (json, xml, html). To do this you change the "Accept" header to either text/html, application/xml or application/json (e.g. Accept: application/xml). You can also use CURL to make HTTP requests and modify the header information.