HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Spring REST / Spring REST Controller Example

Spring REST Controller Example

Learn to create Spring REST controller which can handle REST API calls in any Spring MVC application. It invloves adding @Controller and @RequestMapping annotations.

For writing this application, I am modifying the source code written in Spring MVC example. So, if want, you can download the source code from given link.

1. Update maven dependencies

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

<dependency>
  <groupid>org.codehaus.jackson</groupid>
  <artifactid>jackson-mapper-asl</artifactid>
  <version>${jackson-mapper-asl.version}</version>
  <scope>runtime</scope>
</dependency>

<dependency>
  <groupid>javax.xml.bind</groupid>
  <artifactid>jaxb-api</artifactid>
  <version>${jaxb-api.version}</version>
  <scope>runtime</scope>
</dependency>

2. Add ContentNegotiatingViewResolver

Update bean configuration file for view resolvers and add ContentNegotiatingViewResolver.

<mvc:annotation-driven />

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

<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
    <property name="mediaTypes">
      <map>
          <entry key="html" value="text/html"></entry>
          <entry key="json" value="application/json"></entry>
          <entry key="xml"  value="application/xml"></entry>
      </map>
    </property>
     <property name="viewResolvers">
        <list>
          <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>
          </bean>
        </list>
    </property>
</bean>

3. Add JAXB annotations in model classes

I am writing 2 classes i.e. Users.java and User.java. 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;

@XmlRootElement(name="users")
@XmlAccessorType(XmlAccessType.NONE)
public class Users
{
    @XmlElement(name="user")
    private Collection<User> users;

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

    public void setUsers(Collection<User> users) {
        this.users = users;
    }
}
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;

@XmlRootElement(name="user")
@XmlAccessorType(XmlAccessType.NONE)
public class User {

    @XmlElement(name="first-name")
    private String firstName;

    @XmlElement(name="last-name")
    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;
    }
}

4. Create REST Controller

The DemoController.java has REST specific annotations for path mappings in request parameters mappings. Also, we will specify the header attributes for request and response.

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

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

        User user2 = new User();
        user2.setFirstName("tom");
        user2.setLastName("hanks");

        Users users = new Users();
        users.setUsers(new ArrayList<User>());
        users.getUsers().add(user1);
        users.getUsers().add(user2);

        return users;
    }
}

5. Demo for spring rest example

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

    slash-users-7019076

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

    slash-user-6384669

Download source code

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

Happy Leaning !!

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. vanaja

    August 16, 2019

    In screenshot, output first one is by passing users in URL we will get two employees data. And in the second screenshot passing users/123 in the URL. How the application known that john and adward belongs to the id 123.

    • Lokesh Gupta

      August 16, 2019

      Please refer to latest tutorial.

  2. sonysong

    November 17, 2015

    good tutorial. Easy to understand the concepts with examples.

    One question:
    Why I couldn’t download the example code?

  3. Unknown

    July 16, 2015

    Hi,
    Sir,

    Is there any method to make web service in spring 3 without using maven. please let me know

  4. Imran

    April 21, 2015

    Hi Lokesh,

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

    • Lokesh Gupta

      April 21, 2015

      I will try to find time for this.

      • Imran

        April 22, 2015

        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. 🙂

  5. Teddy

    August 5, 2014

    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?.

    • Lokesh Gupta

      August 5, 2014

      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.

  6. Ricky

    August 1, 2014

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

  7. moez

    July 17, 2014

    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

    • Lokesh Gupta

      July 17, 2014

      Absolutely no problem in doing that. That’s beauty of REST.

  8. divya

    April 15, 2014

    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.

    • Lokesh Gupta

      April 15, 2014

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

      <dependency>
      <groupid>org.codehaus.jackson</groupid>
      <artifactid>jackson-core-asl</artifactid>
      <version>${jackson-core-asl.version}</version>
      <scope>runtime</scope>
      </dependency>

  9. Rakesh Nakod

    February 25, 2014

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

    HTTP Status 406 –

    type Status report

    message

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

    • Rakesh Nakod

      February 25, 2014

      Sorry I meant I added “application/json”

      • Rakesh Nakod

        February 25, 2014

        Resolved the issue.. Adding “jackson-mapper-asl” jar in my lib folder got “application/json” working. 🙂

        • Rakesh Nakod

          February 25, 2014

          Oops.. my bad again 😛 , adding “jackson-core-asl” in my lib folder got “application/json” working. 🙂

          • Lokesh Gupta

            February 25, 2014

            Glad, you made it.

  10. Javier

    September 4, 2013

    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!

    • Lokesh Gupta

      September 5, 2013

      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.

      • Javier

        September 5, 2013

        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.

        • Lokesh Gupta

          September 5, 2013

          Yes, absolutely. And most of annotations here like @Consumes or @Produces are JAX-RS specific, not jersey specific. They will work in any REST implementation.

      • santhosh

        May 18, 2015

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

        • Kishore Anand

          August 14, 2019

          https://github.com/kishore5242/RESTful-web-services/tree/master/spring-restful-services

          Hope this helps!

  11. Vinod

    August 14, 2013

    Hi Lokesh,
    Your blog is awesome and it is really helpful….Thanks alot

  12. Balaji

    April 30, 2013

    How to use

    all
    as of now response is there in xml…

    • howtodoinjava

      April 30, 2013

      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.

  13. Anand Shankar (@anandvns)

    April 8, 2013

    Great 🙂

Comments are closed on this article!

Search Tutorials

Spring REST Tutorials

  • Spring REST – JSON
  • Spring REST – XML
  • Spring REST – Controller
  • Spring REST – CRUD App
  • Spring REST – Exception Handler
  • Spring REST – Request Validation
  • Spring REST – Custom Token Auth
  • Spring REST – Multipart
  • Spring REST – Multiple uploads
  • Spring REST – OPTIONS Handler
  • Spring REST – Access denied JSON
  • Spring REST – RestTemplate

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces