您好,登錄后才能下訂單哦!
在Spring框架中,Thymeleaf是一種流行的模板引擎,用于處理視圖層的渲染。Spring框架通過集成Thymeleaf來實現模板引擎的支持。
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文件內容如下:
<!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模板引擎,并實現視圖層的渲染。Thymeleaf提供了豐富的標簽和表達式,可以方便地構建動態的HTML頁面。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。