springmvc整合thymeleaf
时间: 2023-10-03 15:02:40 浏览: 101
Spring MVC和Thymeleaf的整合非常简单,只需要添加相应的依赖和配置即可。
1. 添加依赖
首先,在pom.xml中添加如下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
```
2. 配置Thymeleaf
在application.properties文件中添加如下配置:
```properties
# 配置Thymeleaf
spring.thymeleaf.mode=HTML
spring.thymeleaf.cache=false
```
3. 配置视图解析器
在Spring的配置类中添加如下配置:
```java
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Bean
public ViewResolver viewResolver() {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(templateEngine());
resolver.setCharacterEncoding("UTF-8");
return resolver;
}
@Bean
public TemplateEngine templateEngine() {
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.setEnableSpringELCompiler(true);
engine.setTemplateResolver(templateResolver());
return engine;
}
private ITemplateResolver templateResolver() {
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setPrefix("classpath:/templates/");
resolver.setSuffix(".html");
resolver.setTemplateMode(TemplateMode.HTML);
resolver.setCharacterEncoding("UTF-8");
resolver.setCacheable(false);
return resolver;
}
}
```
这里使用了ThymeleafViewResolver作为视图解析器,并通过templateEngine()方法配置了模板引擎。
4. 编写Controller和模板
最后,在Controller中返回模板的名称,例如:
```java
@Controller
public class HomeController {
@GetMapping("/")
public String home(Model model) {
model.addAttribute("name", "Thymeleaf");
return "home";
}
}
```
然后,在templates目录下创建home.html模板文件,例如:
```html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Thymeleaf Example</title>
</head>
<body>
<h1>Hello, <span th:text="${name}"></span>!</h1>
</body>
</html>
```
这样就完成了Spring MVC和Thymeleaf的整合。
阅读全文