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:
-
Replace the
@Controllerannotation with@RestController. The@RestControllerannotation is a combination of@Controllerand@ResponseBody, which automatically serializes the returned objects into JSON or XML. -
If you do not want to change the controller annotation, you can add the
@ResponseBodyannotation 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.