Signup/Sign In
PUBLISHED ON: JANUARY 18, 2021

Spring RestController

A RestController is a specialized version of a controller that works with REST services. Spring framework traditionally uses @Controller annotation to create a controller that handles the HTTP requests.

In Spring 4, a new annotation @RestController is added to create a specific controller that is a combined form of @Controller and @RequestBody annotation. It reduces the effort to add every request handling method of the controller with the @ResponseBody annotation.

The purpose of creating RestController is to handle REST service request. Let's understand by example. Here, we created a maven-based spring project that looks like below.

Spring Rest Project Structure

// Appconfig.java

This is a configuration file which is an alternate of the applicationContext.xml file that we created for the XML-based configuration example. The @Configuration annotation indicates that this is not a simple class but a configuration class and the @ComponentScan annotation is used to indicate the location of the component class in our spring project.

package com.studytonight;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@EnableWebMvc
@Configuration
@ComponentScan("com.studytonight.controllers")
public class AppConfig implements WebMvcConfigurer{

	@Autowired
	ApplicationContext applicationContext;

	@Bean
	public ViewResolver viewResolver() {
		InternalResourceViewResolver ivr = new InternalResourceViewResolver();
		ivr.setPrefix("/WEB-INF/views/");
		ivr.setSuffix(".jsp");
		ivr.setOrder(0);
		return ivr;
	}
}

// MainApp.java

This file contains code to create an IOC container for our application. The AnnotationConfigWebApplicationContext class is used to create an object for application context.

package com.studytonight;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class MainApp implements WebApplicationInitializer {

	@Override
	public void onStartup(ServletContext servletContext) throws ServletException { 
		AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
		context.register(AppConfig.class);
		context.setServletContext(servletContext);
		ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(context));
		servlet.setLoadOnStartup(1);
		servlet.addMapping("/");
		context.close();	
	}
}

// HomeController.java

This is controller class but not simple, it is RestController that has two methods getUser() and postUser(), both the methods return a user object in JSON format. To bind the result into Java to JSON, we used the Jackson library in our pom.xml file.

package com.studytonight.controllers;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.studytonight.models.User;

@RestController
public class HomeController {

	@GetMapping("/user")
	public User getUser(@RequestParam(value = "name", defaultValue = "david") String name,
			@RequestParam(value = "lastName", defaultValue = "mark") String lastName,
			@RequestParam(value = "email", defaultValue = "david@gmail.com") String email) {		
		User user = new User();
		user.setName(name);
		user.setLastName(lastName);
		user.setEmail(email);
		return user;
	}
	
	@PostMapping("/user")
	public User postUser(@RequestBody User user) {
		return user;
	}
}

This is the dependency that we need to add to our pom.xml file to bind data into JSON format.

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-databind</artifactId>
	<version>2.10.0.pr3</version>
</dependency>

// User.java

This is a user class that will be used as a bean to hold user data entered from HTML form.

package com.studytonight.models;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
public class User {

	@NotEmpty(message = "Name can not empty")
	String name;
	String lastName;
	@NotEmpty(message = "Email can not empty")
	@Email
	String email;

	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
}

Run the Application

After successfully completing the project and adding the dependencies run the application and you will get the output as below.

If we don't provide values for parameters then it displays the default values set in the controller.

This is how we can pass new values to the controller by using get request and get new data as JSON format.



About the author:
I am a Java developer by profession and Java content creator by passion. I have over 5 years of experience in Java development and content writing. I like writing about Java, related frameworks, Spring, Springboot, etc.