Monday, July 5, 2010

Spring 3: RESTful Web service Support Part-3

1<user>
2 <firstname>Maryfirstname>
3 <lastname>Smithlastname>
4 <preferences>nicepreferences>
5 <preferences>prettypreferences>
6 <preferences>codepreferences>
7 <username>marysusername>
8user>
However, chances are you are not writing this to view some XML in a browser but rather to get or manipulate information from one system or component to another. For this I created a little client, this client uses Springs' RestTemplate which is autowired and lets me access the HTTP functions:

Quote from Spring blog:


DELETE delete(String, String...)
GET getForObject(String, Class, String...)
HEAD headForHeaders(String, String...)
OPTIONS optionsForAllow(String, String...)
POST postForLocation(String, Object, String...)
PUT put(String, Object, String...)


This example only uses getForObject, postForObject, put and delete for the moment, so just the normal CRUD operations.

01package javaitzen.spring.rest.client;
02
03import javaitzen.spring.rest.User;
04
05import org.springframework.beans.factory.annotation.Autowired;
06import org.springframework.stereotype.Component;
07import org.springframework.web.client.RestClientException;
08import org.springframework.web.client.RestTemplate;
09
10@Component("userClient")
11public class UserServiceClient {
12
13 @Autowired
14 protected RestTemplate restTemplate;
15 private final static String serviceUrl ="http://127.0.0.1:7001/Spring3RESTFul-1/app/users/";
16
17 public User retrieveUserDetails(final String firstName) {
18 System.out.println("Client: get");
19 return restTemplate.getForObject(serviceUrl +"{firstName}", User.class, firstName);
20 }
21
22
23 public User createNewUser(final String firstName, final String lastName, final String userName) {
24 System.out.println("Client: post");
25 User newUser = new User(firstName, lastName, userName);
26 newUser = restTemplate.postForObject(serviceUrl, newUser, User.class);
27 return newUser;
28 }
29
30 public void updateUserDetails(final String firstName, finalString lastName, final String userName) {
31 System.out.println("Client: put");
32 User newUser = new User(firstName, lastName, userName);
33 restTemplate.put(serviceUrl + "{firstName}", newUser, firstName);
34 }
35
36 public boolean deleteUserDetails(final String firstName) {
37 System.out.println("Client: delete");
38 try{
39 restTemplate.delete(serviceUrl + "{firstName}", firstName);
40 }catch (RestClientException e) {
41 e.printStackTrace();
42 return false;
43 }
44 return true;
45 }
46
47
48
49}
Now to use the above client I have a test application context injecting the RestTemplate and a test case preforming the create, retrieve, update and delete.

No comments:

Post a Comment