
Question:
i'm new to jEE, and this is my first jEE code using spring. The code bellow is working fine. He just print the string index when i go to my localhost; and otherwise he print handling error.
My question is: Why this code isn't working anymore if I use @Controller
instead of @RestController
I can't find any simple explanation in the docs from spring and I was hoping someone could explain this.
I have the feelings that a controller alone can't work without something like thymeleaf (I know if I were using thymeleaf the string index would be replaced by the index page from the ressources folder) where a RestController might be returning data as xml or json or something else.
Thanks
@RestController
public class HelloController implements ErrorController {
@RequestMapping("/")
public String index() {
return "index";
}
@RequestMapping("/error")
public String error() {
return "gestion erreur";
}
@Override
public String getErrorPath() {
return "/error";
}
}
Answer1:The job of @Controller
is to create a Map of model object and find a view but @RestController
simply return the object and object data is directly written into HTTP response as JSON or XML.
The @Controller
is a common annotation which is used to mark a class as Spring MVC Controller while @RestController
is a special controller used in RESTFul web services and the equivalent of @Controller
+ @ResponseBody
.
If you want the same functionality of @RestController
without using it you can use @Controller
and @ResponseBody
.
@Controller
public class HelloController{
@RequestMapping("/")
@ResponseBody
public String index() {
return "index";
}
}