欢迎光临散文网 会员登陆 & 注册

Springboot中怎么选择性使用thymeleaf进行渲染?

2023-08-05 23:23 作者:艺术人生188  | 我要投稿

Spring Boot 默认支持多种模板引擎,包括 Thymeleaf。如果你想选择性地使用 Thymeleaf 进行渲染,这基本上取决于你的 Controller 的实现。以下是一个基本示例:

首先,确保你的 Spring Boot 项目已经添加了 Thymeleaf 的依赖。在你的 pom.xml 文件中,你应该看到类似以下的内容

<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>

接着,你可以在 Controller 中返回一个 ModelAndView 或者一个 String 来决定是否使用 Thymeleaf 渲染。例如:

@Controller public class MyController {    @RequestMapping("/thymeleaf")    public String thymeleaf(Model model) {        model.addAttribute("message", "Hello, Thymeleaf!");        return "thymeleaf-template";    }    @RequestMapping("/plain")    public ResponseEntity<String> plain() {        return new ResponseEntity<>("Hello, Plain Response!", HttpStatus.OK);    } }

在这个例子中,如果你访问 /thymeleaf URL,那么你的请求将会被渲染成 Thymeleaf 模板(你需要在你的模板目录中有一个名为 thymeleaf-template.html 的文件)。而如果你访问 /plain URL,那么你将会收到一个纯文本的 HTTP 响应,没有使用 Thymeleaf 渲染。

记住,要使 Thymeleaf 渲染生效,你需要在模板目录(默认是 src/main/resources/templates)中有对应的 Thymeleaf 模板文件。

这就是在 Spring Boot 中选择性使用 Thymeleaf 的基本方式。具体的实现可能会根据你的项目需求和架构而有所不同。



Springboot中怎么选择性使用thymeleaf进行渲染?的评论 (共 条)

分享到微博请遵守国家法律