avatarSoma

Summary

The @Controller and @RestController annotations in Spring MVC and Spring Boot are used to define web controllers, with @Controller typically returning HTTP responses with views, while @RestController is designed for REST APIs that return JSON or XML data without requiring the @ResponseBody annotation on each method.

Abstract

In the context of Spring MVC and Spring Boot, @Controller is a foundational annotation used to create web controllers that handle HTTP requests and return view names to be resolved by a view resolver. In contrast, @RestController is a specialized annotation introduced in Spring 3.4 that simplifies the development of RESTful APIs by automatically serializing return values to JSON or XML, effectively combining the @Controller and @ResponseBody annotations. This eliminates the need to annotate each method with @ResponseBody when returning data formats like JSON or XML in a REST API. The article provides code examples to illustrate the differences and offers resources for further learning, including books and online courses focused on Java and Spring Framework interview preparation.

Opinions

  • The author emphasizes the convenience of @RestController for REST API development, as it reduces the need for boilerplate code.
  • The article suggests that developers should be mindful of using @Controller for view-based responses and @RestController for data-based responses.
  • The author provides a subjective recommendation for resources such as books and courses, indicating their potential usefulness for interview preparation.
  • The inclusion of free Spring framework courses suggests the author's support for accessible education and self-study for developers.
  • The author's mention of their own resources, such as the "Grokking the Java Interview" and "Grokking the Spring Boot Interview" eBooks, implies a belief in their effectiveness for interview preparation.

Difference between @Controller and @RestController in Spring Boot and Spring MVC?

@Controller is used to declare common web controllers which can return HTTP response but @RestController is used to create controllers for REST APIs which can return JSON.

image_credit — javarevisited

Hello folks, if you are preparing for Java and Spring Developer interview then you may have come across “difference between @Controller and @RestController annotation” in Spring Boot and Spring Framework in general. It’s one of the popular spring question which I have also mentioned in my list of 25 Spring Framework questions earlier

In Spring MVC, both @Controller and @RestController annotations are used to define web controllers as per MVC Design pattern. A controller is responsible for handling HTTP request and returning HTTP response to client.

The main difference between these two annotation is how they handle client’s request and when they are used

For example @Controller annotation is there from day 1 and it is used to mark a class as a web controller to process HTTP requests and return a view name, which is then resolved by a view resolver to generate the final HTML view.

On the other hand @RestController annotation was added in later Spring version like Spring 3.4 to increase support for REST API development. In case of REST API, instead of returning HTML, you will probably like to return JSON or XML as your client is no more human but machine.

If you want to return a JSON or XML from a Spring MVC controller then you need to add @ReseponseBody annotation to each of Controller method and it seems overkill while implementing REST APIs using Spring and Spring Boot.

Designers and developers of Spring Framework recognized this shortcoming and then added a new annotation called @RestController in Spring 3.4 version.

The @RestController annotation is a combination of the @Controller and @ResponseBody annotations and you can use it to implement REST APIs in Java and Spring Boot.

The key difference between @Controler and @RestController annotation is @ResponseBody annotation, @Controler does not automatically add the @ResponseBody annotation to all of the controller’s methods, which means that you need to add it to each method individually if you want to return a JSON or XML response.@RestController automatically adds the @ResponseBody annotation to all of the controller’s methods.

In the past, I have shared many questions for Java developer interviews like these 35 Java Interview Questions, Advanced Java Interview Questions, Spring Framework Interview Questions and System Design Questions and today, I have answered one of the popular spring question, if you are preparing for interviews, you can also check out those articles.

Now let’s see examples of both @Controller and @RestController annotation in Spring framework

By the way, if you are new to Spring Framework and want to learn Spring in depth and looking for resources then you can also checkout following online courses:

  1. Spring Master Class — Beginner to Expert
  2. Spring & Hibernate for Beginners
  3. Learn Spring: The Certification Class
  4. Master Microservices with Spring Boot and Spring Cloud

All of these are top rated courses to learn Spring framework in depth but if you need free resources you can also checkout these free Spring framework courses:

@Controller and @RestController Example in Spring Boot

Here is a simple example of @Controller annotation which is used to return a response for simple HTTP request on “/hello” path:

@Controller
public class MyController {

    @Autowired
    private MyService myService;

    @RequestMapping("/hello")
    public String sayHello(Model model) {
        model.addAttribute("message", myService.getHelloMessage());
        return "hello";
    }
}

In this example, the MyController class is annotated with @Controller annotation and has a single method, sayHello(), which is mapped to the /hello URL.

The method takes a Model object as a parameter and adds an attribute called "message" to it. The method then returns a string "hello", which is the name of the view to be rendered.

Now, let’s see an example of @RestController annotation from Spring Framework, which i used to respond REST API

@RestController
public class MyRestController {

    @Autowired
    private MyService myService;

    @RequestMapping("/greeting")
    public Greeting getGreeting() {
        return myService.getGreeting();
    }
}

In this example, the MyRestController class is annotated with @RestController and has a single method, getGreeting(), which is mapped to the /greeting URL.

The method returns an object of the Greeting class, which will be automatically converted to a JSON or XML representation and sent as the response to the client.

It is also worth noting that the Greeting class should have getters and setters for the data that you want to be included in the response, otherwise, it will not be serialized properly or converted to JSON.

Things to keep in mind while using @Controller and @RestController annotation in Spring Boot

Here are a few things to keep in mind while using the @Controller and @RestController annotations:

  • When using the @Controller annotation, you will need to use the @ResponseBody annotation to return JSON or XML data, otherwise, the response will be treated as a view name and a view resolver will try to resolve it while @ResponseBody annotation is not necessary as it is already included in the annotation.
  • When using the @RestController annotation, you can also use the @ResponseStatus annotation to set the HTTP status code of the response and @RequestBody annotation to bind the request body to a method parameter.
  • And while using the @RestController annotation, you can use the @RequestMapping annotation to set the URL path to map the methods to.
  • Another thing which is worth noting is that, If you are returning a complex object that contains child objects, make sure all the child object classes have getters and setters, otherwise, they will not be serialized properly.

Java and Spring Interview Preparation Material

Before any Java and Spring Developer interview, I always use to read the below resources

Grokking the Java Interview

Grokking the Java Interview: click here

I have personally bought these books to speed up my preparation.

You can get your sample copy here, check the content of it and go for it

Grokking the Java Interview [Free Sample Copy]: click here

If you want to prepare for the Spring Boot interview you follow this consolidated eBook

Grokking the Spring Boot Interview

You can get your copy here — Grokking the Spring Boot Interview

That’s all about the difference between @Controller and @RestController annotation in Spring Boot. Just remember that @Controller is used to create web controllers that return views, which is further resolved by view resolver, while @RestController is used to create web services that return JSON or XML data. It’s also worth noting.

By the way, if you are new to Spring Framework and want to learn Spring in depth and looking for resources then you can also checkout following online courses:

  1. Spring Master Class — Beginner to Expert
  2. Spring & Hibernate for Beginners
  3. Learn Spring: The Certification Class
  4. Master Microservices with Spring Boot and Spring Cloud

All of these are top rated courses to learn Spring framework in depth but if you need free resources you can also checkout these free Spring framework courses:

My other articles which you may like

Java
Spring Framework
Programming
Spring Boot
Rest Api
Recommended from ReadMedium