Difference between @Controller and @RestController

It is obvious from the previous section that it @RestControlleris a convenient comment, which only adds @Controller and@ResponseBodyNotes .

The main difference between traditional MVC @Controllerand RESTful Web services @RestControlleris the way in which the HTTP response body is created. The rest controller does not rely on view technology to perform the rendering of server-side data to HTML, but simply fills and returns the domain object itself.

Object data will be written directly to the HTTP response in the form of JSON or XML, and parsed by the client to further process it to modify the existing view or for any other purpose.

Using @Controller in spring mvc application
@Controller example without @ResponseBody

@Controller
@RequestMapping("employees")
public class EmployeeController
{
    @RequestMapping(value = "/{name}", method = RequestMethod.GET)
    public Employee getEmployeeByName(@PathVariable String name, Model model) {

        //pull data and set in model

        return employeeTemplate;
    }
}

Using @Controller with @ResponseBody in spring
@Controller example with @ResponseBody

@Controller
@ResponseBody
@RequestMapping("employees")
public class EmployeeController
{
    @RequestMapping(value = "/{name}", method = RequestMethod.GET, produces = "application/json")
    public Employee getEmployeeByName(@PathVariable String name) {

        //pull date

        return employee;
    }
}

Using @RestController in spring
@RestController example

@RestController
@RequestMapping("employees")
public class EmployeeController
{
    @RequestMapping(value = "/{name}", method = RequestMethod.GET, produces = "application/json")
    public Employee getEmployeeByName(@PathVariable String name) {

        //pull date

        return employee;
    }
}

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Hibernate Search - Elasticsearch with JSON manipulation

Spring Elasticsearch Operations