Difference Controller and RestController

Difference Controller and RestController

`@Controller`:

The `@Controller` annotation is used to mark a class as a Spring MVC controller. It indicates that the class will handle web requests and return a view name to be resolved by a view resolver. The controller methods typically return a view name (e.g., JSP, Thymeleaf) and use the `@RequestMapping` (or similar) annotation to map requests to handler methods.

`@RestController`:

The `@RestController` annotation is a specialized version of `@Controller`. It combines `@Controller` and `@ResponseBody` annotations. This means that it not only marks the class as a controller but also ensures that the return value of each handler method is automatically serialized into JSON (or XML) and sent back to the client. This is primarily used for RESTful web services.

Controller and RestController

Example of Controller and RestController

Using @Controller
#HomeController.java
```java
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HomeController {

    @GetMapping("/")
    public String home(Model model) {
        model.addAttribute("message", "Hello, Spring MVC!");
        return "home"; // returns the view name "home"
    }
}
```

#home.jsp
```jsp
<!DOCTYPE html>
<html>
<head>
    <title>Home</title>
</head>
<body>
    <h1>${message}</h1>
</body>
</html>
```

In this example:

The `HomeController` handles HTTP GET requests to the root URL (`/`) and returns the view name `home` The `home.jsp` file is rendered with the model data (`message`).

Example
Using @RestController
#GreetingController.java
```java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GreetingController {

    @GetMapping("/greet")
    public String greet(@RequestParam(name="name", required=false, defaultValue="World") String name) {
        return "Hello, " + name + "!";
    }
}
```

In this example:

  • The GreetingController handles HTTP GET requests to the /greet URL.
  • The method returns a plain string, which is automatically serialized into JSON and sent as the HTTP response.

Project Structure
Project Structure

```
src	
 └── main
     └── java
         └── com
             └── example
                 └── config
                     └── WebConfig.java
                 └── controller
                     └── HomeController.java
                     └── GreetingController.java
     └── resources
         └── application.properties
     └── webapp
         └── WEB-INF
             └── views
                 └── home.jsp
     └── web.xml
```

Maven Dependencies (pom.xml)
 Maven Dependencies (pom.xml)

```xml
<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.3.10</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
        <scope>provided</scope>
    </dependency>
</dependencies>
```

Web Configuration (WebConfig.java)
Web Configuration (WebConfig.java)

```java
package com.example.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.example.controller")
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        registry.jsp("/WEB-INF/views/", ".jsp");
    }
}
```

 

web.xml Configuration
web.xml Configuration

```xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
         http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" 
         version="4.0">
    
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/dispatcher-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>
```

Homepage

Readmore