DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How To Validate HTTP Post Request Body - Restful Web Services With Spring Framework | Spring Boot
  • How To Build Web Service Using Spring Boot 2.x
  • RESTful Web Services With Spring Boot: Reading HTTP POST Request Body
  • Custom Annotations To Validate Input Requests in Spring Boot - Part I

Trending

  • Unlocking AI Coding Assistants Part 1: Real-World Use Cases
  • Optimize Deployment Pipelines for Speed, Security and Seamless Automation
  • Rethinking Recruitment: A Journey Through Hiring Practices
  • From Zero to Production: Best Practices for Scaling LLMs in the Enterprise
  1. DZone
  2. Coding
  3. Frameworks
  4. Spring Framework: @RestController vs. @Controller

Spring Framework: @RestController vs. @Controller

See how you can utilize Spring's annotations to create RESTful web services.

By 
Srivatsan Sundararajan user avatar
Srivatsan Sundararajan
·
Updated Nov. 08, 16 · Tutorial
Likes (84)
Comment
Save
Tweet
Share
280.6K Views

Join the DZone community and get the full member experience.

Join For Free

spring mvc framework and rest

spring’s annotation-based mvc framework simplifies the process of creating restful web services. the key difference between a traditional spring mvc controller and the restful web service controller is the way the http response body is created. while the traditional mvc controller relies on the view technology, the restful web service controller simply returns the object and the object data is written directly to the http response as json/xml.  for a detailed description of creating restful web services using the spring framework, click here .

image title

figure 1: spring mvc traditional workflow

spring mvc rest workflow

the following steps describe a typical spring mvc rest workflow:

  1. the client sends a request to a web service in uri form.
  2. the request is intercepted by the dispatcherservlet which looks for handler mappings and its type.
    • the handler mappings section defined in the application context file tells dispatcherservlet which strategy to use to find controllers based on the incoming request.
    • spring mvc supports three different types of mapping request uris to controllers: annotation, name conventions, and explicit mappings.
  3. requests are processed by the controller and the response is returned to the dispatcherservlet which then dispatches to the view.

in figure 1, notice that in the traditional workflow the modelandview object is forwarded from the controller to the client. spring lets you return data directly from the controller, without looking for a view, using the @responsebody annotation on a method. beginning with version 4.0, this process is simplified even further with the introduction of the @restcontroller annotation. each approach is explained below.

using the @responsebody annotation

when you use the @responsebody annotation on a method, spring converts the return value and writes it to the http response automatically. each method in the controller class must be annotated with @responsebody.

3.x-diagram

figure 2: spring 3.x mvc restful web services workflow

behind the scenes

spring has a list of httpmessageconverters registered in the background. the responsibility of the httpmessageconverter is to convert the request body to a specific class and back to the response body again, depending on a predefined mime type. every time an issued request hits @responsebody, spring loops through all registered httpmessageconverters seeking the first that fits the given mime type and class, and then uses it for the actual conversion.

code example

let’s walk through @responsebody with a simple example.

project creation and setup

  1. create a dynamic web project with maven support in your eclipse or myeclipse ide.
  2. configure spring support for the project. if you are using eclipse ide, you need to download all spring dependencies and configure your pom.xml to contain those dependencies. in myeclipse, you only need to install the spring facet and the rest of the configuration happens automatically.
  3. create the following java class named employee. this class is our pojo.
package com.example.spring.model;

import javax.xml.bind.annotation.xmlrootelement;

@xmlrootelement(name = "employee")
public class employee {

    string name; 
    string email;

    public string getname() {
       return name;
    }

    public void setname(string name) {
      this.name = name;
    }

    public string getemail() {
       return email;
    }

    public void setemail(string email) {
      this.email = email;
    }

    public employee() {
    } 
}


then, create the following @controller class:

package com.example.spring.rest;

import org.springframework.stereotype.controller;
import org.springframework.web.bind.annotation.pathvariable;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestmethod;
import org.springframework.web.bind.annotation.responsebody;

import com.example.spring.model.employee;

@controller
@requestmapping("employees")
public class employeecontroller {
    employee employee = new employee();

    @requestmapping(value = "/{name}", method = requestmethod.get, produces = "application/json")
    public @responsebody employee getemployeeinjson(@pathvariable string name) {

       employee.setname(name);
       employee.setemail("employee1@genuitec.com");

    return employee; 
    }

    @requestmapping(value = "/{name}.xml", method = requestmethod.get, produces = "application/xml")
    public @responsebody employee getemployeeinxml(@pathvariable string name) {

       employee.setname(name);
     employee.setemail("employee1@genuitec.com");

       return employee; 
    }
}

    notice the @responsebody added to each of the @requestmapping methods in the return value. after that, it's a two-step process:

  1. add the <context:component-scan> and <mvc:annotation-driven /> tags to the spring configuration file.
    • <context:component-scan> activates the annotations and scans the packages to find and register beans within the application context.
    • <mvc:annotation-driven/> adds support for reading and writing json/xml if the jackson/jaxb libraries are on the classpath.
    • for json format, include the jackson-databind jar and for xml include the jaxb-api-osgi jar to the project classpath.
  2. deploy and run the application on any server (e.g., tomcat). if you are using myeclipse , you can run the project on the embedded tomcat server .

    json—use the url: http://localhost:8080/springrestcontrollerexample/rest/employees/bob and the following output displays: output_json-crop

    xml — use the
    url: http://localhost:8080/springrestcontrollerexample/rest/employees/bob.xml and the following output displays: output_xml

using the @restcontroller annotation

spring 4.0 introduced @restcontroller, a specialized version of the controller which is a convenience annotation that does nothing more than add the @controller and @responsebody annotations. by annotating the controller class with @restcontroller annotation, you no longer need to add @responsebody to all the request mapping methods. the @responsebody annotation is active by default. click here to learn more.
4.x-diagram

to use @restcontroller in our example, all we need to do is modify the @controller to @restcontroller and remove the @responsebody from each method. the resultant class should look like the following:

package com.example.spring.rest;

import org.springframework.web.bind.annotation.pathvariable;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestmethod;
import org.springframework.web.bind.annotation.restcontroller;

import com.example.spring.model.employee;

@restcontroller
@requestmapping("employees")
public class employeecontroller {

    employee employee = new employee();

    @requestmapping(value = "/{name}", method = requestmethod.get, produces = "application/json")
    public employee getemployeeinjson(@pathvariable string name) {

       employee.setname(name);
       employee.setemail("employee1@genuitec.com");

       return employee;

    }

    @requestmapping(value = "/{name}.xml", method = requestmethod.get, produces = "application/xml")
    public employee getemployeeinxml(@pathvariable string name) {

       employee.setname(name);
       employee.setemail("employee1@genuitec.com");

    return employee; 
    } 
}


note that we no longer need to add the @responsebody to the request mapping methods. after making the changes, running the application on the server again results in the same output as before.

conclusion

as you can see, using @restcontroller is quite simple and is the preferred method for creating mvc restful web services starting from spring v4.0. i would like to extend a big thank you to my co-author, swapna sagi, for all of her help in bringing you this information!

Spring Framework Framework Web Service Annotation Requests

Published at DZone with permission of Srivatsan Sundararajan. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How To Validate HTTP Post Request Body - Restful Web Services With Spring Framework | Spring Boot
  • How To Build Web Service Using Spring Boot 2.x
  • RESTful Web Services With Spring Boot: Reading HTTP POST Request Body
  • Custom Annotations To Validate Input Requests in Spring Boot - Part I

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!