Ant*_*ton 6 spring-mvc thymeleaf spring-boot
我不明白,如果 html 模板与我在 ModelAndView 中获得的属性链接,如何将 @Controller 更改为 @RestController 以获取 RESTFull 服务
@Controller
public class MyController{
@GetMapping("/index")
public ModelAndView index(){
return new ModelAndView("/index", name, userService.getUser().getName());
}
}
Run Code Online (Sandbox Code Playgroud)
在百里香模板中它看起来像
<p th:text="'Hello, ' + ${name} + '!'" />
Run Code Online (Sandbox Code Playgroud)
但我想转到索引页面,并在后台获取用户名
@RestController
public class MyController{
@GetMapping("/api/user")
public String index(){
return userService.getUser().getName();
}
}
Run Code Online (Sandbox Code Playgroud)
我可以使用ajax来更新标签“p”,但这样使用百里香叶没有任何好处,我可以使用jsp。那么休息时使用百里香的最佳方法是什么,它是否合理?
我认为 的目的Thymeleaf
是用于服务器端渲染。
Thymeleaf 是一个 Java 模板引擎,用于处理和创建 HTML、XML、JavaScript、CSS 和文本。
当您使用 JSON API 并解析JSON
并为此使用 angular 或任何其他客户端渲染框架时。Thymeleaf 与 REST 不是方法。
但是,如果您想同时使用两种方式,例如Thymeleaf
向其他应用程序提供数据并向其他应用程序提供 REST 服务,请遵循以下方法。
@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
}
}
Run Code Online (Sandbox Code Playgroud)
我希望这能正确解决您的问题。
归档时间: |
|
查看次数: |
7316 次 |
最近记录: |