springboot調用HTML文件注意事項
1.配置thymeleaf
2.HTML代碼頭部需要添加以下代碼
<link rel="stylesheet" type="text/css" href="/static/css/style.css" rel="external nofollow" th:href="@{css/style.css}" rel="external nofollow" />
其中th為
<html lang="en" xmlns:th="http://www.thymeleaf.org">
3.關于controller和requestmapping
@Controller //只能使用controller,如果使用RestController將只會返回字符串不會返回html頁面 @RequestMapping("/login") ?//此處的request。。。是下面整個模塊的地址,如果想要訪問下面的方法 需要在下面的方法上面單獨請求 public class LoginController { ? ? @RequestMapping("") ?//需要在此處單獨請求 ? ? public String login(){ ? ? ? ? return "/login"; ? ? } }
springboot項目訪問HTML頁面
引入相關依賴
<!--支持跳轉,springboot推薦使用thymeleaf模板引擎--> <dependency> ? ? <groupId>org.springframework.boot</groupId> ? ? <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
<properties> ? ? <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> ? ? <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> ? ? <java.version>1.8</java.version> ? ? <!--指定themleaft版本--> ? ? <thymeleaf.version>3.0.2.RELEASE</thymeleaf.version> ? ? <thymeleaf-layout-dialect.version>2.0.5</thymeleaf-layout-dialect.version> </properties>
增加springboot配置項
#thymeleaf模版前綴 spring.thymeleaf.prefix=classpath:/templates/
在 src/main/resources 目錄下新建 static 目錄和 templates 目錄。 static存放靜態文件,templates 存放靜態頁面(thymeleaf 模版)
在控制器中寫明跳轉模版方法
Handler訪問映射地址跳轉模版成功
總結這次遇到的問題
1.?Error resolving template template might not exist or might not be accessible
控制器方法返回的模版名稱沒有前綴/,可手動添加/或添加springboot配置項
2.?org.xml.sax.SAXParseException: 元素類型 “link” 必須由匹配的結束標記 “” 終止,org.xml.sax.SAXParseException: 元素類型 “meta” 必須由匹配的結束標記 “” 終止
開發工具生成的html頁面元素有的沒有終止符/,thymeleaf模板引擎默認是Template modes:HTML5解析的,解析比較嚴格。
需要手動添加/或指定引入的thymeleaf版本號
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持。
原文地址:https://blog.csdn.net/qq_45904712/article/details/123961624