SpringBoot使用thymeleaf模板

SpringBoot开发的WEB项目Contrller如何跳转到前端页面

目前Spring官方已经不推荐使用JSP来开发WEB了,而是推荐使用如下几种模板引擎来开发:

  • Thymeleaf(Spring官方推荐)
  • FreeMarker
  • Velocity
  • Groovy
  • Mustache

据说,最流行的还是FreeMarker和Velocity这两种模板,我们这里用Spring官方推荐的Thymeleaf模板

在创建好SpringBoot项目的基础上,进行如下配置:

  1. 在POM中到Thymeleaf的依赖

    <!--对HTML的依赖-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    
  2. 在application.properties中设置模板寻找路径

    # 模板引擎读取路径
    # 是让controller层到templates文件夹寻找xx.html(src/main/resources/templates)
    spring.thymeleaf.prefix=classpath:/templates/
    
  3. 在resource/templates目录下创建html页面,如index.html

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        在SpringBoot项目中使用HTML页面<br>
        获取页面上传过来的参数PPP:<p th:text="${param1}"></p>
    </body>
    </html>
    
  4. 创建Controller类

    @Controller
    //  这里不能是RestController注解,不然会输出index字符串
    public class HelloWorld {        
        @RequestMapping("/toIndexPage")
        public String getHtmlPage(HashMap<String, Object> map){
            map.put("param1", "hello world");
            return "index"; // 这里的字符串对应html的文件名(不包含后缀)
        }       
    }
    
  5. 访问项目

    http://localhost:8080/toIndexPage        

猜你喜欢

转载自www.cnblogs.com/baimeishaoxia/p/11810362.html