How to write RESTful web services using spring 3 mvc

You have learned that how to write the RESTful web services and also how to write Spring 3 web application. Now, its time to combine them so that your spring web application shall work like RESTful webservices also.

Download source code

For writing this application, I am modifying the source code written in previous post. So, if want, you can download from there or you have it from above download link.

Step 1) Update pom.xml to add support of JAXB and Jackson (for xml and json formats).



Do not forget to run “mvn eclipse:eclipse -Dwtpversion=2.0” command on command prompt again, to update the project dependencies.

Step 2) Update bean configuration file (spring-mvc-servlet.xml) for view resolvers.

<mvc:annotation-driven />

<context:component-scan  base-package="com.howtodoinjava.web" />

<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
	<property name="mediaTypes">
		  <entry key="html" value="text/html"></entry>
		  <entry key="json" value="application/json"></entry>
		  <entry key="xml"  value="application/xml"></entry>
	 <property name="viewResolvers">
		  <bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
			<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
			<property name="prefix" value="/WEB-INF/jsp/"></property>
			<property name="suffix" value=".jsp"></property>

Step 3) Add model classes I am writing 2 classes i.e. and These classes will be having JAXB annotations, which will be used by marshaller to convert them in appropriate xml or json formats. They are for example only and you can write your own classes.

package com.howtodoinjava.model;

import java.util.Collection;

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

public class Users
	private Collection<User> users;

	public Collection<User> getUsers() {
		return users;

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

Now write

package com.howtodoinjava.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;

public class User {

	private String firstName;

	private String lastName;

	public String getFirstName() {
		return firstName;
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	public String getLastName() {
		return lastName;
	public void setLastName(String lastName) {
		this.lastName = lastName;

Step 4) Update the controller Our will modified to have REST specific annotations for path mappings in request parameters mappings. Also, we will specify the header attributes for request and response.

public class DemoController
	@RequestMapping(method = RequestMethod.GET, value="/{id}", headers="Accept=*/*")
	public @ResponseBody User getUserById(@PathVariable String id)
		User user = new User();
		return user;

	@RequestMapping(method = RequestMethod.GET,  headers="Accept=*/*")
	public @ResponseBody Users getAllUsers()
		User user1 = new User();

		User user2 = new User();

		Users users = new Users();
		users.setUsers(new ArrayList<User>());

		return users;

Now lets re-deploy the application on tomcat and hit the URL on any REST client. I am using RESTClient. This is a firefox plugin for testing the RESTful webservices.

URL : http://localhost:8080/firstSpringApplication/users


URL : http://localhost:8080/firstSpringApplication/users/123


Download source code

Drop me a comment if it really helped you, or you have any query.

Happy Leaning !!

25 thoughts on “How to write RESTful web services using spring 3 mvc”
  1. Hi Lokesh,

    Your blog is nice , but i am looking sring mvc+ jersey configuration example.
    could you please post this example also .

      1. Hi Lokesh,

        One more thing. If we want to change Spring mvc + Jersey –> Spring mvc + Resteasy configuration what are the changes needs for this.
        because i tried couple of tutorial but I didn’t get any solution for the same.
        Thanks, Waiting for your post for the same. :-)

  2. Hi Lokesh
    Your blog is nice. I need to enable the existing web application to expose its API as rest services.
    Can you please provide some sample for that?. Adding jersey jars and annotations would complete the implementation. I need a sample app without rest implementation then adding the rest services to show the difference before and after?.

    1. I do not have any sample application for this. Please do not annotate your existing controller classes with JAX-RS/Jersey annotations. Always create “NEW” web-service specific classes at controller layer. Once you get the request at these controllers, and then use existing application infrastructure (e.g. managers, DAOs etc.) using dependency injection.
      If you use existing controller classes and modified them, then you will end up making lots of “design compromises e.g. URL patterns and HATEOAS”. Having them separate makes your job as easy as writing new APIs from scratch.

  3. Thank you for a great post. I tested it. both application/json and application/xml worked, but the text/html does not. any thought?

  4. can you help me please if i create this rest webservice So i can apply with another client for example with client service in c# or not

  5. I have tried to follow all steps mentioned in the blog above. I still get the error “description The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request “accept” headers.”. I am able to generate o/p in xml format, but I get this error while trying to generate the response in json format.

    1. You need to add dependency for “jackson-core-asl” as well.


  6. Tried adding “application/xml” as “accept” header in request header.Getting the following error.

    HTTP Status 406 –

    type Status report


    description The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request “accept” headers.

  7. Great example!,

    I have a question, when I try to call the web service from another client (no local) I have the following message:

    “is not allowed by Access-Control-Allow-Origin”,

    But in the method header I see this code:

    @RequestMapping(method = RequestMethod.GET, value=”/{id}”, headers=”Accept=*/*”)

    What code Do I have to add over there?

    Thanks a lot!

    1. Probably you are accessing rest API from another application, that’s why you are seeing this problem. This is not REST implementation specific. It needs to be resolved at application configuration level.

      1. thanks, I have to configurate my app.
        Does your demo can send json parameters too? I tried to send it like jersey (@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) but it doesn’t work.

        Thanks a lot, I just discovered your blog.

      2. Hi how to integrate spring
        +rest webservive +hibernate (using annotations) if you have any example please post …..thank you

    1. Hi Bala, if you see the very first image, i have passed “application/xml” as “accept” header in request. So, the returned response is in xml.
      If you want to get response in json, then send the accept header as “applicatio/json”. The same goes for html also.

Note:- In comment box, please put your code inside [java] ... [/java] OR [xml] ... [/xml] tags otherwise it may not appear as intended.

Leave a Reply

Your email address will not be published. Required fields are marked *

four × = 28

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>