Spring RestTemplate CRUD operations with XML


Spring RESTFul Client – RestTemplate Example with CRUD operations using XML


CRUD stands for Create,Read,Update and Delete operation

These are the most common operations that we perform in any application.

CRUD_operation_JAXB_Table

Let’s do these operations using Spring Rest service with RestTemplate client.

Requirement :

Perform CRUD operations on USER object.

We have User Domain object, we can insert User data, read the inserted data,

Update some user information and finally delete the user data.

Create a new Maven Web project in eclipse (Refer Spring MVC Hello World project for the same)

Project structure


rest_template__spring_crud_xml_proj_structure

Please refer Spring Rest CRUD XML Project for the below files

1)pom.xml
2)web.xml
3)UserService.java
4)UserDAO.java

Step 1

Create a domain class which represents the data in XML format

create User.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.kb.rest.model;
 
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
 
@XmlRootElement(name="User")
@XmlAccessorType(XmlAccessType.FIELD)
public class User {
    @XmlElement(name="Name")
    private String name;
    @XmlElement(name="Age")
    private int age;
    @XmlElement(name="Id")
    private int id;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
}
package com.kb.rest.model;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="User")
@XmlAccessorType(XmlAccessType.FIELD)
public class User {
	@XmlElement(name="Name")
	private String name;
	@XmlElement(name="Age")
	private int age;
	@XmlElement(name="Id")
	private int id;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
}

We have created a User class with id,name and age to represent the data

create UserDetailsResponse.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.kb.rest.model;
 
import java.util.List;
 
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
 
@XmlRootElement(name="UserList")
@XmlAccessorType(XmlAccessType.FIELD)
public class UserDetailsResponse {
    
    @XmlElement(name="User")
    private List<User> users;
 
    public List<User> getUsers() {
        return users;
    }
 
    public void setUsers(List<User> users) {
        this.users = users;
    }
 
 
}
package com.kb.rest.model;

import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="UserList")
@XmlAccessorType(XmlAccessType.FIELD)
public class UserDetailsResponse {
	
	@XmlElement(name="User")
	private List<User> users;

	public List<User> getUsers() {
		return users;
	}

	public void setUsers(List<User> users) {
		this.users = users;
	}


}

We have created a UserDetailsResponse class which contains the List of User.

@XmlRootElement – specifies the root element in xml.

@XmlElement – specifies the child element which comes under root element in XML

We will perform CRUD operations on these objects.

Why do we need to create UserDetailsResponse class when we already have User class ?
Reason is very simple,When we use Rest Template as a client, internally it uses HttpMessageConverters to convert the request/response into appropriate object.
So when we get List of user as a response , we need some POJO class to map this response.(User class will be mapped only to single User)
Hence we need to write this POJO class.

Step 2

Create the resource mapping class which will have the URL mapping methods for all our CRUD operations

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.kb.rest.controllers;
 
import java.util.List;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
 
import com.kb.rest.model.User;
import com.kb.rest.model.UserDetailsResponse;
import com.kb.rest.service.UserService;
 
@Controller
@RequestMapping("/user")
public class RestController {
 
    @Autowired
    private UserService userService;
    
    // CRUD -- CREATE operation
    @RequestMapping(value = "/create", method = RequestMethod.POST,consumes=MediaType.APPLICATION_XML_VALUE,produces=MediaType.APPLICATION_XML_VALUE)
    public @ResponseBody User createUser(@RequestBody User user) {
        User userResponse = userService.createUser(user);
        return userResponse;
    }
 
    // CRUD -- READ operation
    @RequestMapping(value = "/getAllUsers", method = RequestMethod.GET,produces=MediaType.APPLICATION_XML_VALUE)
    public @ResponseBody UserDetailsResponse getAllUsers() {
        List<User> userList = userService.getAllUsers();
        UserDetailsResponse userDetailsResponse = new UserDetailsResponse();
        userDetailsResponse.setUsers(userList);
        return userDetailsResponse;
    }
 
    // CRUD -- READ operation
    @RequestMapping(value = "/getSpecificUser/{id}", method = RequestMethod.GET,produces=MediaType.APPLICATION_XML_VALUE)
    public @ResponseBody User getUserForId(@PathVariable ("id") int id) {
        User user = userService.getUserForId(id);
        return user;
    }
 
    // CRUD -- UPDATE operation
    @RequestMapping(value = "/updateUser", method = RequestMethod.PUT,consumes=MediaType.APPLICATION_XML_VALUE,produces=MediaType.APPLICATION_XML_VALUE)
    public @ResponseBody User updateUser(@RequestBody User user) {
        User userResponse = userService.updateUser(user);
        return userResponse;
    }
 
    // CRUD -- DELETE operation
    @RequestMapping(value = "/deleteUser/{id}", method = RequestMethod.DELETE,produces=MediaType.APPLICATION_XML_VALUE)
    public @ResponseBody User deleteeUser(@PathVariable("id") int id) {
        User userResponse = userService.deleteUser(id);
        return userResponse;
    }
}
package com.kb.rest.controllers;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kb.rest.model.User;
import com.kb.rest.model.UserDetailsResponse;
import com.kb.rest.service.UserService;

@Controller
@RequestMapping("/user")
public class RestController {

	@Autowired
	private UserService userService;
	
	// CRUD -- CREATE operation
	@RequestMapping(value = "/create", method = RequestMethod.POST,consumes=MediaType.APPLICATION_XML_VALUE,produces=MediaType.APPLICATION_XML_VALUE)
	public @ResponseBody User createUser(@RequestBody User user) {
		User userResponse = userService.createUser(user);
		return userResponse;
	}

	// CRUD -- READ operation
	@RequestMapping(value = "/getAllUsers", method = RequestMethod.GET,produces=MediaType.APPLICATION_XML_VALUE)
	public @ResponseBody UserDetailsResponse getAllUsers() {
		List<User> userList = userService.getAllUsers();
		UserDetailsResponse userDetailsResponse = new UserDetailsResponse();
		userDetailsResponse.setUsers(userList);
		return userDetailsResponse;
	}

	// CRUD -- READ operation
	@RequestMapping(value = "/getSpecificUser/{id}", method = RequestMethod.GET,produces=MediaType.APPLICATION_XML_VALUE)
	public @ResponseBody User getUserForId(@PathVariable ("id") int id) {
		User user = userService.getUserForId(id);
		return user;
	}

	// CRUD -- UPDATE operation
	@RequestMapping(value = "/updateUser", method = RequestMethod.PUT,consumes=MediaType.APPLICATION_XML_VALUE,produces=MediaType.APPLICATION_XML_VALUE)
	public @ResponseBody User updateUser(@RequestBody User user) {
		User userResponse = userService.updateUser(user);
		return userResponse;
	}

	// CRUD -- DELETE operation
	@RequestMapping(value = "/deleteUser/{id}", method = RequestMethod.DELETE,produces=MediaType.APPLICATION_XML_VALUE)
	public @ResponseBody User deleteeUser(@PathVariable("id") int id) {
		User userResponse = userService.deleteUser(id);
		return userResponse;
	}
}

We have created the Controller class above which will act as a Rest service in Spring.

We have @RequestBody along with method parameter in POST and PUT methods which indicates to Spring that ,the request for this method will be coming as a HTTP request body with specified MIME type and it is mapped with a parameter of a method.

We have @ResponseBody before the return type of a method in method signature which indicates to Spring that ,the returned value from this method will not be a view rather it has to be read from the response body.

@PathVariable :
It is used to get the parameter value passed along with the URL.
Its very similar to @PathParam in JAX-RS.

@PathVariable(“id”) int id
This will get the value passed in the URL and inject it to id variable of method argument.

consumes=MediaType.APPLICATION_XML_VALUE
This is used to specify that the Rest service is capable of consuming XML input.

produces=MediaType.APPLICATION_XML_VALUE
This is used to specify that the Rest service is capable of producing XML output

Step 3

Create Rest Clients using RestTemplate as below

PostUserClient.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.kb.rest.client;
 
import org.springframework.web.client.RestTemplate;
 
import com.kb.rest.model.User;
 
public class PostUserClient {
    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();
        final String url = "http://localhost:8080/SpringRestCRUDXML/user/create";
        User user = new User();
        user.setId(1);
        user.setAge(45);
        user.setName("John");
        User addedUser = restTemplate.postForObject(url, user, User.class);
        System.out.println("User Inserted is : " + addedUser.getName());
    }
}
package com.kb.rest.client;

import org.springframework.web.client.RestTemplate;

import com.kb.rest.model.User;

public class PostUserClient {
	public static void main(String[] args) {
		RestTemplate restTemplate = new RestTemplate();
		final String url = "http://localhost:8080/SpringRestCRUDXML/user/create";
		User user = new User();
		user.setId(1);
		user.setAge(45);
		user.setName("John");
		User addedUser = restTemplate.postForObject(url, user, User.class);
		System.out.println("User Inserted is : " + addedUser.getName());
	}
}

In this client , we are making a POST call with User details using postForObject() method of RestTemplate

It takes 3 parameters which are
url – the end point of the Rest service
user – object which has to be submitted to rest service
User.class – type of the object

After posting, we are getting the same object as a response and we are displaying its details.

GetUsersClient.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.kb.rest.client;
 
import org.springframework.web.client.RestTemplate;
 
import com.kb.rest.model.User;
import com.kb.rest.model.UserDetailsResponse;
 
public class GetUsersClient {
    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();
        final String url = "http://localhost:8080/SpringRestCRUDXML/user/getAllUsers";
        UserDetailsResponse userDetailsResponse = restTemplate.getForObject(url, UserDetailsResponse.class);
        System.out.println("User retrieved details : ");
        for (User user : userDetailsResponse.getUsers()) {
            System.out.println(user.getName() + " " + user.getAge() + " " + user.getId());
        }
 
    }
 
}
package com.kb.rest.client;

import org.springframework.web.client.RestTemplate;

import com.kb.rest.model.User;
import com.kb.rest.model.UserDetailsResponse;

public class GetUsersClient {
	public static void main(String[] args) {
		RestTemplate restTemplate = new RestTemplate();
		final String url = "http://localhost:8080/SpringRestCRUDXML/user/getAllUsers";
		UserDetailsResponse userDetailsResponse = restTemplate.getForObject(url, UserDetailsResponse.class);
		System.out.println("User retrieved details : ");
		for (User user : userDetailsResponse.getUsers()) {
			System.out.println(user.getName() + " " + user.getAge() + " " + user.getId());
		}

	}

}

In this client , we are making a GET call to get All Users details using getForObject() method of RestTemplate

It takes 2 parameters which are
url – the end point of the Rest service
UserDetailsResponse.class – type of the response object

After Get call, we are getting userDetailsResponse object as a response which contains the List of Users and we are displaying each user details.

GetSpecificUserClient.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.kb.rest.client;
 
import org.springframework.web.client.RestTemplate;
 
import com.kb.rest.model.User;
 
public class GetSpecificUserClient {
    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();
        final String url = "http://localhost:8080/SpringRestCRUDXML/user/getSpecificUser/1";
        User user = restTemplate.getForObject(url, User.class);
        System.out.println("User retrieved details : ");
        System.out.println(user.getName() + " " + user.getAge() + " " + user.getId());
 
    }
}
package com.kb.rest.client;

import org.springframework.web.client.RestTemplate;

import com.kb.rest.model.User;

public class GetSpecificUserClient {
	public static void main(String[] args) {
		RestTemplate restTemplate = new RestTemplate();
		final String url = "http://localhost:8080/SpringRestCRUDXML/user/getSpecificUser/1";
		User user = restTemplate.getForObject(url, User.class);
		System.out.println("User retrieved details : ");
		System.out.println(user.getName() + " " + user.getAge() + " " + user.getId());

	}
}

In this client , we are making a GET call to get only single User details using getForObject() method of RestTemplate

It takes 2 parameters which are
url – the end point of the Rest service
User.class – type of the response object

After Get call, we are getting User object as a response which contains the User details and we are displaying the same.

PutUserClient.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.kb.rest.client;
 
import org.springframework.web.client.RestTemplate;
 
import com.kb.rest.model.User;
 
public class PutUserClient {
    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();
        final String url = "http://localhost:8080/SpringRestCRUDXML/user/updateUser";
        User user = new User();
        user.setId(1);
        user.setAge(20);
        user.setName("John1");
        restTemplate.put(url, user);
 
        // Verify updated user details
        final String getUrl = "http://localhost:8080/SpringRestCRUDXML/user/getSpecificUser/1";
        User updatedUser = restTemplate.getForObject(getUrl, User.class);
        System.out.println("User updated details : ");
        System.out.println(updatedUser.getName() + " " + updatedUser.getAge() + " " + updatedUser.getId());
 
    }
}
package com.kb.rest.client;

import org.springframework.web.client.RestTemplate;

import com.kb.rest.model.User;

public class PutUserClient {
	public static void main(String[] args) {
		RestTemplate restTemplate = new RestTemplate();
		final String url = "http://localhost:8080/SpringRestCRUDXML/user/updateUser";
		User user = new User();
		user.setId(1);
		user.setAge(20);
		user.setName("John1");
		restTemplate.put(url, user);

		// Verify updated user details
		final String getUrl = "http://localhost:8080/SpringRestCRUDXML/user/getSpecificUser/1";
		User updatedUser = restTemplate.getForObject(getUrl, User.class);
		System.out.println("User updated details : ");
		System.out.println(updatedUser.getName() + " " + updatedUser.getAge() + " " + updatedUser.getId());

	}
}

In this client , we are making a PUT call with User details using put() method of RestTemplate

It takes 2 parameters which are
url – the end point of the Rest service
user – object which has to be updated by rest service

After posting, we are making a GET call with the same id and displaying the updated details.

DeleteUserClient.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.kb.rest.client;
 
import org.springframework.web.client.RestTemplate;
 
import com.kb.rest.model.User;
 
public class DeleteUserClient {
    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();
        final String url = "http://localhost:8080/SpringRestCRUDXML/user/deleteUser/3";
        restTemplate.delete(url);
 
        // Verify updated user details
        final String getUrl = "http://localhost:8080/SpringRestCRUDXML/user/getSpecificUser/3";
        User deletedUser = restTemplate.getForObject(getUrl, User.class);
        System.out.println("Deleted user details : " + deletedUser);
 
    }
}
package com.kb.rest.client;

import org.springframework.web.client.RestTemplate;

import com.kb.rest.model.User;

public class DeleteUserClient {
	public static void main(String[] args) {
		RestTemplate restTemplate = new RestTemplate();
		final String url = "http://localhost:8080/SpringRestCRUDXML/user/deleteUser/3";
		restTemplate.delete(url);

		// Verify updated user details
		final String getUrl = "http://localhost:8080/SpringRestCRUDXML/user/getSpecificUser/3";
		User deletedUser = restTemplate.getForObject(getUrl, User.class);
		System.out.println("Deleted user details : " + deletedUser);

	}
}

In this client , we are making a DELETE call by passing User Id as part of URL using delete() method of RestTemplate

It takes 1 parameter which is
url – the end point of the Rest service

After the Delete call, we are making a GET call with the same id and displaying the updated details.

Step 4

Build and deploy the project

Step 5

Let’s see the output of all CRUD operations

POST

Run PostUserClient.java

output

we can see the user inserted details in the output

GET

Run GetUsersClient.java

output

we can see the List of Users available in the output

GET with specific user ID

Run GetSpecificUserClient.java

output

we can see the user details for a user with ID 1

PUT

Run PutUserClient.java

output

we can see that User name has been updated and we can see the same in the output as “John1”

DELETE

Run DeleteUserClient.java

output

we can see that User has been deleted and requesting to get the same user is giving as null in the output.

Download this project SpringRestCRUDXMLRestTemplate.zip

About the Author

Karibasappa G C (KB)
Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on