Thursday 6 July 2017

Spring MVC Java Config : Part 3 RESTful Web Services


REST stands for Representational State Transfer.

It’s an is an architectural style which can be used to design web services, that can be consumed from a variety of clients.

The core idea is that, rather than using complex mechanisms such as CORBA, RPC or SOAP to connect between machines, simple HTTP/HTTPS is used to make calls among them.


1. TOOLS AND ENV

IDE : Spring Tool Suite 3.7.3
JDK : 1.8
Tomcat : 8.0.18
Spring : 4.2.6.RELEASE




2. POM.XML


1. add spring-oxm for jaxb
2. add jackson-databind for json




3. RestController



1. @RestController annotation marks all the methods with @RequestMapping becoming @ResponseBody
2.  JAXB won't be able to handle List<ToDoEntity> ,  we must create a wapper in case of converting from list of java beans to XML
3. Below are the patterns for restful web services , we would code GET and POST here , others are similar
  • GET request to /api/todo/ returns a list of todos    
  • GET request to /api/todo/1 returns the todo with ID 1
  • POST request to /api/todo/ with a todo object as JSON creates a new todo    
  • PUT request to /api/todo/3 with a todo object as JSON updates the todo with ID 3
  • DELETE request to /api/todo/4 deletes the todo with ID 4
  • DELETE request to /api/todo/ deletes all the users




4. POJO




1.@XmlAccessorType(XmlAccessType.NONE) , JAXB will create bindings for annotated fields and methods
2. @XmlAnyElement(lax=true) annotation, what this means is that when dealing with this property the @XmlRootElement of the referenced object will be used.  If lax is set to false then the content will be unmarshalled as DOM nodes.





5. ADD MESSAGE CONVERTER TO SPRING MVC


1. you may see some of spring mvc tutorial use Jaxb2RootElementHttpMessageConverter for JAXB, refer below on why it is not perferred
https://jira.spring.io/browse/SPR-13530
https://jira.spring.io/browse/SPR-10262
2. JAXB would fail at EntityList<T> without below line which add all classes under the package to JAXB context
marshaller.setPackagesToScan("com.cn.junjun.spring.sample.bean");





6. JSP FOR RESTful WS







7. JS for JSP








8. TEST with POSTMAN




POSTMAN test scripts are available here : https://www.getpostman.com/collections/cc404ecd3f8648e83827

 




9. SOURCE CODE

https://github.com/junjun-dachi/spring-4-samples/tree/master/spring-4-mvc-sample-03





Reference :

1. https://spring.io/blog/2013/05/11/content-negotiation-using-spring-mvc 
2. https://spring.io/guides/gs/rest-service/
3. http://spring.io/guides/tutorials/bookmarks/





No comments:

Post a Comment

Flag Counter