總結
- thymeleaf的模板解析規則不清楚,或者忘了;
- 出現bug時,瞎調試, 沒有打開NETWORK 進行查看資源的加載情況
- 控制器中的其他代碼,可以先注釋掉,這樣就可以迅速屏蔽掉其他代碼的影響.
- thymeleaf重寫href超鏈接的時候, 注意格式: href="asserts/css/bootstrap.min.css" th:href="@{/asserts/css/dashboard.css}" ,asserts前加上'/';
- 在js腳本中src也需要進行thymeleaf重寫, src="asserts/js/Chart.min.js" th:src="@{/asserts/js/Chart.min.js};
問題描述
-
通過路徑1跳轉,正常加載
-
通過路徑2跳轉,加載失敗 莫名其妙地多出現了emp路徑 ,並且頁面的樣式全無
springboot控制器的寫法
//4.來到修改頁面,查出當前員工,在頁面回顯,進而修改員工信息頁面
@GetMapping("/emp/{id}")
public String toEditPage(@PathVariable Integer id,Model model){
Employee employee = employeeDao.get(id);
System.out.println(employee);
model.addAttribute("emp",employee);
//頁面要顯示所有的部門列表
Collection<Department> departments = departmentDao.getDepartments();
model.addAttribute("depts",departments);
System.out.println(departments);
//回到修改頁面,add.html 是一個修改添加二合一的頁面
return "/emp/add.html";
}
找到上面的圖中的 Bootstrap core JavaScript 等 靜態資源的所在位置
<!-- Bootstrap core CSS -->
<link href="asserts/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="asserts/css/dashboard.css" rel="stylesheet">
<style type="text/css">
/* Chart.js */
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script type="text/javascript" src="asserts/js/jquery-3.2.1.slim.min.js"></script>
<script type="text/javascript" src="asserts/js/popper.min.js"></script>
<script type="text/javascript" src="asserts/js/bootstrap.min.js"></script>
問題分析
- thymeleaf有動態模板渲染的功能, 沒有使用thymeleaf將靜態資源的位置進行重寫;
- 控制器沒問題,不用瞎改半天;
- ```js
只要我們把HTML頁面放在classpath:/templates/,thymeleaf就能自動渲染;
public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";
**同樣的,如果加了html/css等后綴,thymeleaf就不再渲染,不在"classpath:/templates/"文件夾里的,也是不進行渲染的.**
```
- **因此,如上代碼需要進行按照thymeleaf的語法進行再次引用重寫, 可保證路徑的引用正確**
代碼重寫
<!-- Bootstrap core CSS -->
<link href="asserts/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="asserts/css/dashboard.css" th:href="@{/asserts/css/dashboard.css}" rel="stylesheet">
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script type="text/javascript" src="asserts/js/jquery-3.2.1.slim.min.js" th:src="@{/asserts/js/jquery-3.2.1.slim.min.js}"></script>
<script type="text/javascript" src="asserts/js/popper.min.js" th:src="@{/asserts/js/popper.min.js}"></script>
<script type="text/javascript" src="asserts/js/bootstrap.min.js" th:src="@{/asserts/js/bootstrap.min.js}"></script>