Controller class in spring
To initialize the controller in the spring we need the below annotations
@Controller:
- this is a specialization of the @Componet annotation.
- the controller annotation indicates that the class is a controller type to spring while component scanning.
- by default, @Controller handler methods only return the view.
- if we want to return JSON or XML response then need to add @ResponseBody annotation on every method in the class.
@Controller
public class HelloWordController {
@RequestMapping("/showform")
public String showForm() {
return "helloword-form";
}
@RequestMapping("/showform2")
@RequestBody
public User showForm() {
return new User("Nilesh","Kadam");
}
}
@RestController :
- @RestController is a specialized version of @Controller annotation. this is a combination of @Controller and @ResponseBody annotation.
- RestController is useful for RESTfull web service because in RESTfull web service we only return the data not view.
- in this, we do not require to add @ResponseBody on every method
@RestController
public class HelloWordController {
@RequestMapping("/showform")
public User showForm() {
return new User("Nilesh","Kadam");
} }
Comments
Post a Comment