springbootの簡単な紹介(5-2):フロントエンドインターフェイス-thymeleafテンプレートエンジン

テンプレートエンジン

SpringBootでは、テンプレートエンジンを使用してhtmlをレンダリングすることをお勧めします。履歴プロジェクトでない場合は、JSPを使用しないでください。freemark、thymeleafなど、一般的に使用されるテンプレートエンジンは多数ありますが、すべて同じです。
その中で、springbootはthymeleafを強くお勧めします

1)pomファイルタイプのthymeleafサポートを追加し、JSPサポートを削除します。

  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <!--&lt;!&ndash;JavaServer Pages Standard Tag Library,JSP标准标签库&ndash;&gt;-->
        <!--<dependency>-->
            <!--<groupId>javax.servlet</groupId>-->
            <!--<artifactId>jstl</artifactId>-->
        <!--</dependency>-->
        <!--&lt;!&ndash;内置tocat对Jsp支持的依赖,用于编译Jsp&ndash;&gt;-->
        <!--<dependency>-->
            <!--<groupId>org.apache.tomcat.embed</groupId>-->
            <!--<artifactId>tomcat-embed-jasper</artifactId>-->
        <!--</dependency>-->

2)application.propertiesファイルのビューパーサーのコンテンツを削除します。

~~#spring.mvc.view.prefix=/WEB-INF/jsp/
#spring.mvc.view.suffix=.jsp~~ 

3)新しいコントローラーの内容は次のとおりです。

package cn.enjoy.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/tpl")
public class ThymeleafController {
    
    
    @RequestMapping("/testThymeleaf")
    public String testThymeleaf(ModelMap map) {
    
    
     // 设置属性
     map.addAttribute("name", "enjoy");
     // testThymeleaf:为模板文件的名称
     // 对应src/main/resources/templates/testThymeleaf.html
     return "testThymeleaf";
 }
}

4)Springbootのデフォルトのテンプレート構成パスは次のとおりです。src / main / resources / templates
resourcesディレクトリに新しいtemplatesディレクトリを作成し、ディレクトリに新しいtestThymeleaf.htmlファイルを作成します。

<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head lang="en">
    <meta charset="UTF-8" />
    <title>enjoy</title>
</head>
<body>
<h1 th:text="${name}"/>
</body>
</html>
	在浏览器上输入:localhost:8080/tpl/testThymeleaf,可以看到页面。

前の章:springbootの簡単な紹介(5-1):フロントエンドインターフェイス-Jsp統合

おすすめ

転載: blog.csdn.net/weixin_46822085/article/details/109306645