Difference between @Controller vs @RestController in Spring Framework

Hello and welcome to the blog post. If you are preparing for Java or Spring Boot interview, you may have come across this topic. In this article, we are going to have a look at the difference between @Controller and @RestController annotation. Let's understand with the help of an example.
Spring Framework is a popular open-source application framework that provides infrastructure support for developing Java applications. One of the essential components of Spring Framework is the controller, which is used to handle HTTP requests and provide responses to clients. In Spring, there are two types of controllers: @Controller and @RestController.

In this article, we will discuss the differences between @Controller and @RestController and when to use each one. Although both of them are used for handling HTTP requests, they have some fundamental differences


What is @Controller Annotation in Spring MVC? What does it do?

The @Controller is a Spring annotation used to mark a class as a controller. The main purpose of a controller is to handle HTTP requests and return a response to the client. The @Controller is used to build traditional web applications, where the primary goal is to return a view to the client.

A view is a server-side template that is rendered on the client side, typically with the help of HTML, CSS, and JavaScript. The view contains the presentation layer of the application, which is responsible for displaying data to the user. 

The controller's primary role is to collect data from various sources, process it, and provide it to the view, which will display it to the user.

Example of @Controller annotation:

Let's consider a simple example of a controller that returns a view to the client. Suppose we have a controller named CarController that handles the request to the root URL. Here's how I have defined the CarController:

@Controller

public class CarController {

    

    @RequestMapping("/")

    public String getCar() {

        return "car";

    }

}

In this example, we have annotated the CarController class with the @Controller annotation, which indicates that this class is a controller. The @RequestMapping("/") annotation maps the root URL to the getCar() method. The getCar() method returns a String "car", which is the name of the view that we want to render.




What is @RestController Annotation in Spring?

On the other hand, @RestController is used to build RESTful web services, where the primary goal is to return data to the client in a structured format like JSON or XML. The data returned by a RESTful service is typically consumed by another application or system, rather than a human user.

 

Example of @RestController

Let's consider a simple example of a RESTful controller that returns data as JSON to the client. Suppose we have a controller named BikeController that handles the request to get a list of bikes. Here's how we can define the BikeController:


@RestController

public class BikeController {



    @GetMapping("/bikes")

    public List<Bikes> getBikes() {

        List<Bike> bikes = new ArrayList<>();

        bikes.add(new Bike(1, "Silver Stallion", "Honda"));

        bikes.add(new Bike(2, "The Comet", "Yamaha"));

        return bikes;

    }

}

In this example, we have annotated the BikeController class with the @RestController annotation, which indicates that this class is a RESTful controller. The @GetMapping("/bikes") annotation maps the "/bikes" URL to the getBikes() method. The getBikes() method returns a List of Bike objects, which will be automatically converted to JSON by Spring.


Differences between @Controller and @RestController in Spring MVC

The fundamental differences between @Controller and @RestController are as follows:


1. Response Type

The primary difference between @Controller and @RestController is the response type they return. As we have mentioned earlier @Controller annotation typically returns a view name, that later resolves to get HTML view using a view resolver.

Whereas @RestController was included in Spring 3.4 version to support REST API development. REST APIs are helpful, if your client is not a human but a computer, you would generally prefer to deliver JSON or XML instead of HTML.

It is to note here that, the Controller class in the Spring framework has the task of generating a model Map containing information to be presented by the view, and also selecting the appropriate view. Additionally, the Controller can utilize the @ResponseBody annotation to directly write to the response stream and finalize the request. 

This means by adding the following two annotations, we can make it behave exactly like @RestController

In short, @Controller + @ResponseBody = @RestController



Request Mapping

Another difference between @Controller and @RestController is the way they handle HTTP requests. In @Controller, we use the @RequestMapping annotation to map an HTTP request to a method in the controller. 

The @RequestMapping annotation is a general-purpose annotation that can be used to handle any HTTP request method (GET, POST, PUT, DELETE, etc.). 

In contrast, @RestController uses more specific annotations like @GetMapping, @PostMapping, @PutMapping, and @DeleteMapping to handle HTTP requests.

For example, in a @Controller class, we might define a method like this to handle a GET request:

@Controller

public class CarController {

    @RequestMapping(value = "/", method = RequestMethod.GET)

    public String getCar(Model model) {

        return "car";

    }

}


In contrast, in a @RestController class, we would use the @GetMapping annotation to handle the same request:

@RestController

public class BikeController {



    @GetMapping("/bikes")

    public List<Bikes> getBikes() {

        List<Bike> bikes = new ArrayList<>();

        bikes.add(new Bike(1, "Silver Stallion", "Honda"));

        bikes.add(new Bike(2, "The Comet", "Yamaha"));

        return bikes;

    }

}

As you can see, the @RestController version is more concise and easier to read than the @Controller version. The use of more specific annotations makes the code more readable and easier to understand.


Default Response Type

By default, @Controller returns a view, while @RestController returns data in a structured format like JSON or XML. In a @Controller, if we don't explicitly specify a response type, Spring assumes that we want to return a view. 

In contrast, in a @RestController, if we don't explicitly specify a response type, Spring assumes that we want to return data in a structured format.

For example, consider the following @Controller method:

@Controller

public class CarController {   

    @RequestMapping("/")

    public String getCar(Model model) {

        model.addAttribute("carName", "Bonbon");

        return "car";

    }

}



In this example, we are returning to a view named "car". Spring framework assumes that we want to return a view because we have not explicitly specified a response type. In contrast, consider the following @RestController method:

@RestController

public class CarController {   

    @GetMapping("/")

    public String home() {

        return "Car Details";

    }

}

In this example, we are returning a string "Car Details". Spring assumes that we want to return data in a structured format because we have used @RestController annotation.


Conclusion

That's all about difference between @Controller and @RestController annotation in Spring MVC and Spring Boot. In this article, I have tried by best to explain the difference between the two annotations i.e. @Controller and @RestController in Spring MVC and REST. The key difference between @RestController and @Controller which is worth remember is that @RestController is a shorthand to use @Controller and @ResponseBody annotations together. 

This annotation was purposely added by Spring in Spring 4 to facilitate the creation of RESTful web services using the Spring framework. Depending on the MIME type of the request, it can directly transform the answer to JSON or XML.

So, if you are creating a RESTful Web Services it’s better to use @RestController than combining the @Controller to @ResponseBody.

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.