Spring MVC Controller

The Spring Controller annotation is a more specific version of the @Component annotation. It is commonly used with annotated handler methods that are based on the RequestMapping annotation.

Spring Controller – A controller component in the Spring framework.

The Controller annotation can only be used on classes and is utilized to designate a class as a handler for web requests. This annotation is predominantly employed in Spring MVC applications.

Spring RestController can be rephrased as “Spring’s RestController” or “RestController provided by Spring.”

The Spring @RestController annotation is a shortcut for @Controller and @ResponseBody combined, typically used to indicate that a class serves as a request handler for RESTful web services.

An example of a Spring Controller.

Spring Controller Example Project
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-webmvc</artifactId>
	<version>5.0.7.RELEASE</version>
</dependency>
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-web</artifactId>
	<version>5.0.7.RELEASE</version>
</dependency>

<!-- Jackson for REST -->
<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-databind</artifactId>
	<version>2.9.6</version>
</dependency>

In this case, we will examine the deployment descriptor (web.xml) to set up the DispatcherServlet servlet as the primary controller.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns="https://xmlns.jcp.org/xml/ns/javaee" 
 xsi:schemaLocation="https://xmlns.jcp.org/xml/ns/javaee https://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>Spring-Controller</display-name>
  <!-- Add Spring MVC DispatcherServlet as front controller -->
	<servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>
                org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <init-param>
       		<param-name>contextConfigLocation</param-name>
       		<param-value>/WEB-INF/spring-servlet.xml</param-value>
    		</init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
 
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/</url-pattern> 
    </servlet-mapping>
</web-app>

Lastly, we possess the subsequent spring context file. In this file, we set up our application for annotation-based configuration and specify the root package to scan for spring components. Additionally, we configure the InternalResourceViewResolver bean and provide specifics about the view pages.

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="https://www.springframework.org/schema/mvc"
	xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns:beans="https://www.springframework.org/schema/beans"
	xmlns:context="https://www.springframework.org/schema/context"
	xsi:schemaLocation="https://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
		https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
		https://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

	<!-- Enables the Spring MVC @Controller programming model -->
	<annotation-driven />

	<context:component-scan base-package="com.scdev.spring" />

	<!-- Resolves views selected for rendering by @Controllers to JSP resources 
		in the /WEB-INF/views directory -->
	<beans:bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>

</beans:beans>

Our Controller class will be our next focus as our configuration XML files have been prepared.

package com.scdev.spring.controller;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HomeController {

	@GetMapping("/hello")
	public String home(Locale locale, Model model) {
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		String formattedDate = dateFormat.format(date);
		model.addAttribute("serverTime", formattedDate);
		return "home";
	}

}

We have created a request handler method specifically for receiving GET requests with the URI “/hello” and responding with the “home.jsp” page. It is important to note that we have also assigned a value to a model attribute, which will be utilized on the home.jsp page. Below is the code for our straightforward home.jsp page.

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<html>
<head>
<title>Home</title>
</head>
<body>
	<h1>Hello world!</h1>

	<p>The time on the server is ${serverTime}.</p>

</body>
</html>

Testing of Spring MVC Controllers

Spring Controller Example

Example of a Spring RestController.

Let’s now enhance our application to also provide REST APIs. Develop a model class that will be transmitted as a JSON response.

package com.scdev.spring.model;

public class Person {

	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
}

This is our elementary REST Controller class.

package com.scdev.spring.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.scdev.spring.model.Person;

@RestController
public class PersonRESTController {

	@RequestMapping("/rest")
	public String healthCheck() {
		return "OK";
	}

	@RequestMapping("/rest/person/get")
	public Person getPerson(@RequestParam(name = "name", required = false, defaultValue = "Unknown") String name) {
		Person person = new Person();
		person.setName(name);
		return person;
	}

}

Please test our REST APIs by redeploying the application once more.

Testing the REST Controller of Spring.

Spring REST Controller Example

Give me a single option to paraphrase the following natively: “Provide a brief overview.”

The Spring Controller serves as the foundation for Spring MVC applications, initiating our business logic. Additionally, the RestController simplifies the creation of REST-based web services.

The example project code is available for download on our GitHub Repository.

 

more tutorials

Spring Component annotation(Opens in a new browser tab)

Spring MVC HandlerInterceptorAdapter and HandlerInterceptor.(Opens in a new browser tab)

One example of Spring REST XML and JSON(Opens in a new browser tab)

Spring Boot CLI(Opens in a new browser tab)

React Application Component Testing Integrate with Playwright(Opens in a new browser tab)

 

Leave a Reply 0

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