When comes to developing applications using Spring frameworks, what are the difference between Spring @RestController and @Controller? This post is going to talk about the difference between @RestController and @Controller in simply.

@Controller

In the earlier time, @Controller is commonly used traditional SpringMVC application development. By this method, it without isolation of the back-end corresponding to the front-end case. The workflow like the following image.

SpringMVC workflow

For example:

@Controller
public class HelloController {
    @GetMapping("/hello")
    public String greeting(@RequestParam(name = "name", required = false, defaultValue = "World") String name, Model model) {
        model.addAttribute("name", name);
        return "hello";
    }
}

When a request comes, Spring will look for a “hello” view in the templates directory under the resources directory. (It is recommended to place the views pages in the resources/templates directory).

hello.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Getting Started: Serving Web Content</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<p th:text="'Hello, ' + ${name} + '!'"/>
</body>
</html>

@Controller + @ ResponseBody returns data in JSON or XML

To develop RESTful web services, you can use @Controllercombine @ResponseBodyannotations. That is same as using @RestController(new annotations added after Spring 4).

@Controller + @ ResponseBody returns data in JSON or XML

The @ResponseBody annotation acts the role Controllerthat converted the object returned to the specified format by a suitable converter, and to write to the HTTP response body objects. JSON or XML is typically used to return data, and the JSON used more commonly.

For example:

Person.java

public class Person {
    private String name;
    private Integer age;
    ......
    ...constructor,setter,getter...
}

HelloController.java

@Controller
public class HelloController {
    @PostMapping("/hello")
    @ResponseBody
    public Person greeting(@RequestBody Person person) {
        return person;
    }
}

Visit http: // localhost: 8080 / hello, you will get the result like

{
    "name": "etbye.com",
    "age": 21
}

@RestController returns data in JSON or XML

@RestController only returns the object data, and the object data is directly written into the HTTP response in JSON or XML. This situation belongs to RESTful web services, which is also the most commonly used in daily development.

SpringMVC RESTful workflow

Check out the RESTful web service demo as following.