Sobes.tech
Junior — Middle

What methods can be used to convert a regular Spring MVC controller into a REST controller?

sobes.tech AI

Answer from AI

To convert a regular Spring MVC controller to a REST controller, you can use the following methods:

  1. Replace the @Controller annotation with @RestController. The @RestController annotation is a combination of @Controller and @ResponseBody, which automatically serializes the returned objects into JSON or XML.

  2. If you do not want to change the controller annotation, you can add the @ResponseBody annotation to each method to indicate that the return value should be written to the HTTP response body.

Example:

// Regular controller
@Controller
public class MyController {
    @RequestMapping("/hello")
    @ResponseBody
    public String hello() {
        return "Hello World";
    }
}

// REST controller
@RestController
public class MyRestController {
    @RequestMapping("/hello")
    public String hello() {
        return "Hello World";
    }
}

Thus, the simplest way is to replace @Controller with @RestController.

What methods can be used to convert a regular Spring… - sobes.tech