springboot整合thymeleaf跳转html页面

1、在pom.xml文件中添加Thymeleaf依赖。确保引入了spring-boot-starter-thymeleaf依赖,如下所示:

<dependencies>
    <!-- 其他依赖 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
</dependencies>

2、配置Thymeleaf模板引擎。在application.properties或application.yml文件中添加以下配置:
application.properties:

spring.thymeleaf.enabled=true
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

application.yml:

spring:
  thymeleaf:
    enabled: true
    prefix: classpath:/templates/
    suffix: .html

3、创建HTML页面。在src/main/resources/templates/目录下创建HTML文件,例如welcome.html,并在该文件中编写需要展示的内容,例如:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Welcome Page</title>
</head>
<body>
    <h1>Welcome, <span th:text="${name}"></span>!</h1>
</body>
</html>

4、创建Controller类,并编写相应的请求处理方法。例如,创建一个WelcomeController类,定义一个处理欢迎页面请求的方法,如下所示:

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class WelcomeController {
    
    
    
    @GetMapping("/welcome")
    public String welcomePage(@RequestParam("name") String name, Model model) {
    
    
        model.addAttribute("name", name);
        return "welcome";
    }
}

在上面的例子中,welcomePage方法接受一个名为name的请求参数,并将其传递给Thymeleaf模板的name变量。
5、启动应用程序并访问对应的URL。启动Spring Boot应用程序,并在浏览器中访问/welcome?name=JohnURL,将会跳转到welcome.html页面,并显示欢迎消息。
跳转页面展示

在页面中,Thymeleaf的语法${name}将会被替换为John,因为我们在Controller方法中将name参数传递给了模型。
这样,就完成了Spring Boot整合Thymeleaf的示例,并演示了如何进行页面跳转和数据展示。你可以根据自己的需求在Thymeleaf模板中添加更多动态数据,以及使用Thymeleaf提供的丰富的表达式和指令来实现更复杂的功能。

猜你喜欢

转载自blog.csdn.net/scj0725/article/details/131292080