springboot不使用thymeleaf
时间: 2023-04-27 09:01:56 浏览: 72
Spring Boot可以使用其他模板引擎,如Freemarker、Velocity、Mustache等。如果不想使用模板引擎,也可以直接返回JSON数据或者HTML页面。可以使用@RestController注解来返回JSON数据,使用@Controller注解来返回HTML页面。
相关问题
springboot 如何使用thymeleaf
要在Spring Boot中使用Thymeleaf,需要完成以下步骤:
1. 在pom.xml文件中添加Thymeleaf依赖项:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
```
2. 在Spring Boot应用程序的配置文件application.properties中添加以下配置:
```properties
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
```
这里的配置指定了模板文件的位置和后缀名。
3. 在Spring Boot应用程序中创建一个控制器类,用于处理请求和响应:
```java
@Controller
public class MyController {
@GetMapping("/")
public String home(Model model) {
model.addAttribute("message", "Hello, World!");
return "home";
}
}
```
这里的控制器处理根路径请求,并将一个名为"message"的属性添加到模型中,然后返回"home"字符串,它是模板文件的名称。
4. 在src/main/resources/templates目录下创建home.html文件:
```html
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1 th:text="${message}"></h1>
</body>
</html>
```
这里的模板文件包含一个<h1>标签,它使用Thymeleaf表达式来显示"message"属性的值。
5. 运行Spring Boot应用程序,访问http://localhost:8080/,应该能够看到"Hello, World!"。
这样,就完成了在Spring Boot中使用Thymeleaf的基本配置和使用。
运行springboot项目使用Thymeleaf
要在Spring Boot项目中使用Thymeleaf,需要进行以下步骤:
1. 在pom.xml文件中添加Thymeleaf的依赖
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
```
2. 在application.properties中添加Thymeleaf的配置
```
# 模板文件所在目录
spring.thymeleaf.prefix=classpath:/templates/
# 后缀
spring.thymeleaf.suffix=.html
# 是否开启缓存
spring.thymeleaf.cache=false
# 字符编码
spring.thymeleaf.encoding=UTF-8
```
3. 在Controller中添加请求处理方法并返回对应的Thymeleaf模板名称
```
@Controller
public class MyController {
@RequestMapping("/index")
public String index() {
return "index";
}
}
```
4. 在resources/templates下创建对应的Thymeleaf模板文件