您好,登錄后才能下訂單哦!
在Spring框架中,Thymeleaf是一種流行的模板引擎,用于處理視圖層的渲染。Spring框架通過集成Thymeleaf來實(shí)現(xiàn)模板引擎的支持。
Spring框架中支持Thymeleaf的步驟如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
@Configuration
public class ThymeleafConfig {
@Bean
public ClassLoaderTemplateResolver templateResolver() {
ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
templateResolver.setPrefix("templates/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("HTML");
templateResolver.setCharacterEncoding("UTF-8");
return templateResolver;
}
@Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
return templateEngine;
}
@Bean
public ThymeleafViewResolver viewResolver() {
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
viewResolver.setCharacterEncoding("UTF-8");
return viewResolver;
}
}
例如,index.html文件內(nèi)容如下:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Hello Thymeleaf</title>
</head>
<body>
<h1 th:text="${message}"></h1>
</body>
</html>
@Controller
public class HelloWorldController {
@RequestMapping("/")
public String hello(Model model) {
model.addAttribute("message", "Hello Thymeleaf!");
return "index";
}
}
通過以上步驟,Spring框架就能夠支持Thymeleaf模板引擎,并實(shí)現(xiàn)視圖層的渲染。Thymeleaf提供了豐富的標(biāo)簽和表達(dá)式,可以方便地構(gòu)建動(dòng)態(tài)的HTML頁面。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。