springboot输出到html参数
时间: 2024-01-07 11:05:57 浏览: 79
在Spring Boot中,可以使用Thymeleaf模板引擎将数据渲染到HTML页面中。以下是一个简单的示例:
1. 在pom.xml文件中添加Thymeleaf依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
```
2. 创建一个Controller类,定义一个处理请求的方法:
```java
@Controller
public class MyController {
@GetMapping("/hello")
public String hello(Model model) {
model.addAttribute("name", "World");
return "hello";
}
}
```
3. 创建一个Thymeleaf模板文件hello.html:
```html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Hello</title>
</head>
<body>
<h1>Hello, <span th:text="${name}"></span>!</h1>
</body>
</html>
```
4. 运行应用程序并访问http://localhost:8080/hello,就会看到“Hello, World!”输出在页面上。
在这个例子中,我们使用了Thymeleaf的属性替换语法,将模型中的"name"属性替换到了HTML页面中。如果你想输出其他类型的参数,可以使用Thymeleaf的内置表达式。例如,如果要输出日期和时间,可以使用以下代码:
```html
<p>Today is <span th:text="${#dates.format(today, 'dd/MM/yyyy')}"></span></p>
<p>The time is <span th:text="${#dates.format(today, 'HH:mm:ss')}"></span></p>
```
在这个例子中,我们使用了Thymeleaf的#dates对象来格式化日期和时间。注意,我们还需要将日期对象添加到模型中:
```java
@Controller
public class MyController {
@GetMapping("/time")
public String time(Model model) {
model.addAttribute("today", new Date());
return "time";
}
}
```
这样,在访问http://localhost:8080/time时就会输出当前日期和时间。
阅读全文
相关推荐















