Spring @RestController vs @Controller

To understand the difference between @RestController and @Controller we can think about the main difference between a REST API and a Web application. The response of a REST API is generally JSON or XML; in a web application, instead, the response is usually a view (some html + css) intended for human viewers.

This is also the main difference between @Controller and @RestController annotation. Basically in a spring mvc @Controller the handler method returns the response “view name” which is resolved to a view technology file (e.g. JSP) and the parsed view content is sent back to browser client. It just create a map of the model object and find a view. If we want instead to bundle the return value yo a web response body we can use the @ResponseBody annotation and no view resolver is needed.

For example assuming that we have a view and a greeting Api in a MVCController that take a param as input and return a view we can use @Controller annotation

// Path of view template
/src/main/resources/templates/greeting.html

@Controller
public class MVCController {

    @RequestMapping("/greeting")
    public String greeting(@RequestParam(name = "name", required = 
              false, defaultValue = "World") String name, Model model) {
        model.addAttribute("name", name);
        // We can return a view name that is present in 
        return "greeting";
    }
}

The @RestController simply returns the object and object data is directly written into HTTP response as JSON or XML. One notice is that in Spring MVC the @RestController annotation is a combination of @Controller and @ResponseBody annotation.

@Controller
@ResponseBody
public class MVCController {
  // your logic
}

@RestController
public class RestFulController { 
  // your logic
}

Leave a Reply

Your email address will not be published.

*