why this Model thing works on @Controller but doesnt work on @RestController
when i try
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@Controller
public class ArticleController {
@GetMapping("/articles")
public String getArticles(Model model) {
List<Article> articles = articleService.findAllArticles();
model.addAttribute("articles", articles);
return "articleList";
}
@GetMapping("/article/{id}")
public String getArticleById(@PathVariable Long id, Model model) {
Article article = articleService.findArticleById(id);
model.addAttribute("article", article);
return "articleDetail";
}
}
it works, but exact same code with @RestController intead of @Controller
don’t work
hamdam is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
The main difference and the reason why it is not working is what each controller returns.
@RestController returns in most of the time JSON, while on other side @Controller returns a string that represents a view name that is either HTML,JSP,etc.
@Controller: This is used to define a controller that handles web requests and returns view names. The view names are resolved by a view resolver, such as a JSP page or a Thymeleaf template. In this case, the Model object is used to pass data to the view layer, which is typically an HTML page.
@RestController: This is a convenience annotation that combines @Controller and @ResponseBody. It is used to create RESTful web services. When you use @RestController, Spring converts the returned objects directly into JSON or XML responses. This means that there is no view resolution happening, and hence, the Model object is not applicable in this context.