I don't understand, how to change @Controller to @RestController for RESTFull serivce, if html template linked with attributes that I get in ModelAndView
@Controller
public class MyController{
@GetMapping("/index")
public ModelAndView index(){
return new ModelAndView("/index", name, userService.getUser().getName());
}
}
and in thymeleaf template it's look like
<p th:text="'Hello, ' + ${name} + '!'" />
But I wanna go to index page, and in background get user name
@RestController
public class MyController{
@GetMapping("/api/user")
public String index(){
return userService.getUser().getName();
}
}
I can use ajax for update tag "p", but in this way it's nothing benefit of using thymeleaf, I can use jsp. So what the best way use thymeleaf with rest and is it rational?
Thymeleaf offers a set of Spring integrations that allow you to use it as a fully-featured substitute for JSP in Spring MVC applications.
Thymeleaf with REST is not the approach. If you have JS frameworks then provide using REST API ( big trend in industry) or If you have server rendering technology then use MV object from spring framework.
1. Overview. Thymeleaf is a Java template engine for processing and creating HTML, XML, JavaScript, CSS and text. In this tutorial, we will discuss how to use Thymeleaf with Spring along with some basic use cases in the view layer of a Spring MVC application.
Thymeleaf is way better in my opinion because it have good underlying priciples and exploits natural behaviour of browsers. Jsp makes html hard to read, it becomes weird mixture of html and java code which makes a lot of problems in comunication between designer - developer.
I think the purpose of Thymeleaf
is for server-side rendering.
Thymeleaf is a Java template engine for processing and creating HTML, XML, JavaScript, CSS, and text.
When you are using JSON API and parse the JSON
and use angular or any other client-side rendering framework for that. Thymeleaf with REST is not the approach.
But if you want to use both ways like provide data to Thymeleaf
and also provide REST services to other application follow below approach.
@RequestMapping('/foobars')
abstract class FoobarBaseController {
@RequestMapping
abstract listAll()
}
@Controller
class FoobarHtmlController extends FoobarBaseController {
@Override ModelAndView listAll() {
new ModelAndView('foobars/foobarThymeleafTemplate', [foobars: foobarsList])
}
}
@RestController
@RequestMapping('/foobars', produces = MediaType.APPLICATION_JSON_VALUE)
class FoobarJsonController extends FoobarBaseController {
@Override Collection<Foobar> listAll() {
foobarsList
}
}
I hope this address your question properly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With