SpringBoot使用thymeleaf模板

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

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

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

听说,最流行的仍是FreeMarker和Velocity这两种模板,咱们这里用Spring官方推荐的Thymeleaf模板spring

在建立好SpringBoot项目的基础上,进行以下配置:app

  1. 在POM中到Thymeleaf的依赖spring-boot

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

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

    <!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类xml

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

    http://localhost:8080/toIndexPage
相关文章
相关标签/搜索