1、資源存放目錄說明
static
今天資源
templates
頁面,templates只能通過 controller來訪問
resources
也可以存放資源文件
public
SpringBoot 源碼中找到的,靜態資源公共的可以放在這裏
2、Thymeleaf 使用,導入靜態資源模板 使用html 編寫頁面
-
導入對應maven依賴
<!-- thymeleaf依賴,如果要編寫頁面一定需要這個依賴 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
-
編寫 html 頁面放到 templates 目錄下
-
使用controller 進行跳轉
@Controller // 可以被視圖解析器解析 public class IndexController { // 只要訪問了 / 就會跳轉到 templates目錄下的 index 頁面 // SpringBoot 要使用默認的模板引擎 thymeleaf 一定需要導入其對應的依賴! @RequestMapping("/") public String index(){ System.out.println("1111"); return "index"; } }
-
啓動項目請求測試,看是否可以跳轉 html 頁面!
頁面傳遞值
1、在後端方法中使用 Model 傳遞值
2、在前端使用 th:xxx 去接收後端傳遞值,注意:一定要導入頭文件約束
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>首頁</h1>
<!-- 普通取值 -->
<p th:text="${msg}"></p>
<!-- 循環遍歷 接收後端傳遞的 users,遍歷每個的結果就是user,可以再這個標籤內使用!
th:each="item:items"
-->
<h2 th:each="user:${users}" th:text="${user}"></h2>
<!-- 行內寫法 -->
<h2 th:each="user:${users}">[[${user}]]</h2>
<div th:each="user:${users}">
<p th:text="${user}"></p>
</div>
</body>
</html>
實現一個基本的小網站
- 目錄結構:
1、新建一個SPringboot項目,構建web模塊
2、導入pojo 和 dao 的類
Department
package com.zj.pojo;
public class Department {
private Integer id;
private String departmentName;
public Department() {
}
public Department(int i, String string) {
this.id = i;
this.departmentName = string;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
@Override
public String toString() {
return "Department [id=" + id + ", departmentName=" + departmentName + "]";
}
}
Employee
package com.zj.pojo;
public class Department {
private Integer id;
private String departmentName;
public Department() {
}
public Department(int i, String string) {
this.id = i;
this.departmentName = string;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
@Override
public String toString() {
return "Department [id=" + id + ", departmentName=" + departmentName + "]";
}
}
3、導入靜態資源(頁面放在 Templeate,資源 放在 static目錄下)
4、所有頁面增加頭文件 xmlns:th="http://www.thymeleaf.org">
5、所有的資源鏈接修改格式爲thymeleaf 語法 th:xxx='@'
6、可以增加一個配置類,配置我們的SpringMVC(瞭解即可)
@Configuration // 代表這是一個配置類
public class MyMvcConfig implements WebMvcConfigurer {
// 通過配置類來設置視圖跳轉
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("/index.html").setViewName("index");
registry.addViewController("/main.html").setViewName("dashboard");
}
@Bean
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}
// 註冊攔截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 選擇要過濾和排除的請求
registry.addInterceptor(new LoginHandlerInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/index.html","/","/user/login")
.excludePathPatterns("/asserts/**");
}
}
7、我們可以設置項目的路徑名,application.properties
#關閉緩存
spring.thymeleaf.cache=false
#國際化配置
spring.messages.basename=i18n.login
#時間日期格式化
spring.mvc.date-format=yyyy-MM-dd
增加登錄和攔截的功能以及註銷功能!
- 寫一個登錄和註銷的控制類
@Controller
public class UserController {
// 登錄實現
@RequestMapping("/user/login")
public String login(@RequestParam("username") String username,
@RequestParam("password") String password,
Model model, HttpSession session){
if (!StringUtils.isEmpty(username) && "123456".equals(password)){
// 登錄成功, 利用重定向可以防止表單重複提交
session.setAttribute("loginUser",username);
return "redirect:/main.html";
}else {
model.addAttribute("msg","用戶名或者密碼錯誤");
return "index";
}
}
@RequestMapping("/user/logout")
public String logout(HttpSession session){
session.invalidate();
return "redirect:/main.html";
}
}
- 登錄界面.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Signin Template for Bootstrap</title>
<!-- Bootstrap core CSS -->
<link th:href="@{/asserts/css/bootstrap.min.css}" rel="stylesheet">
<!-- Custom styles for this template -->
<link th:href="@{/asserts/css/signin.css}" rel="stylesheet">
</head>
<body class="text-center">
<form class="form-signin" th:action="@{/user/login}">
<img class="mb-4" th:src="@{/asserts/img/bootstrap-solid.svg}" alt="" width="72" height="72">
<h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1>
<!--判斷是否有錯誤信息-->
<p th:if="${not #strings.isEmpty(msg)}" th:text="${msg}" style="color: red"></p>
<label class="sr-only">Username</label>
<input type="text" class="form-control" name="username" th:placeholder="#{login.username}" required="" autofocus="">
<label class="sr-only">Password</label>
<input type="password" class="form-control" name="password" th:placeholder="#{login.password}" required="">
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me">[[#{login.remember}]]
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">[[#{login.btn}]]</button>
<p class="mt-5 mb-3 text-muted" >© 2017-2018</p>
<a class="btn btn-sm" th:href="@{/index.html(l='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/index.html(l='en_US')}">English</a>
</form>
</body>
</html>
- 設置登錄攔截器
public class LoginHandlerInterceptor implements HandlerInterceptor {
// 判斷是否攔截
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Object loginUser = request.getSession().getAttribute("loginUser");
if (loginUser==null){
request.setAttribute("msg","沒有權限,請先登錄");
request.getRequestDispatcher("/index.html").forward(request,response);
return false;
}else {
return true;
}
}
}
國際中英文轉換
我們在resources資源文件下新建一個i18n目錄,建立一個login.propetries文件,還有一個login_zh_CN.properties,發現IDEA自動識別了我們要做國際化操作;文件夾變了
我們可以在這上面去新建一個文件;
彈出如下頁面:我們再添加一個英文的;
這樣就快捷多了!
接下來,我們就來編寫配置,我們可以看到idea下面有另外一個視圖;
這個視圖我們點擊 + 號就可以直接添加屬性了;我們新建一個login.tip,可以看到邊上有三個文件框可以輸入
我們添加一下首頁的內容!
然後依次添加其他頁面內容即可!
然後去查看我們的配置文件;
login.properties : 默認
login.btn=登錄
login.password=密碼
login.remember=記住我
login.tip=請登錄
login.username=用戶名
英文:
login.btn=Sign in
login.password=Password
login.remember=Remember me
login.tip=Please sign in
login.username=Username
中文:
login.btn=登錄
login.password=密碼
login.remember=記住我
login.tip=請登錄
login.username=用戶名
第三步 : 去頁面獲取國際化的值;
查看Thymeleaf的文檔,找到message取值操作爲: #{…}。
我們去頁面測試下;
我們可以去打開項目,訪問一下,發現已經自動識別爲中文的了!
在Spring中有一個國際化的Locale (區域信息對象);裏面有一個叫做LocaleResolver (獲取區域信息對象)的解析器
public class MyLocaleResolver implements LocaleResolver {
@Override
public Locale resolveLocale(HttpServletRequest request) {
String language = request.getParameter("l");
Locale locale = Locale.getDefault();
if (!StringUtils.isEmpty(language)){
String[] split = language.split("_");
locale=new Locale(split[0],split[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
}
}
修改一下前端頁面的跳轉連接;
增改查功能
員工列表功能
要求 : 我們需要使用 Restful風格實現我們的crud操作!
看看一些具體的要求,就是我們小實驗的架構;
我們在主頁點擊Customers,就顯示列表頁面;我們去修改下
1.將首頁的側邊欄Customers改爲員工管理
2.a鏈接添加請求
<a class="nav-link" href="#" th:href="@{/emps}">員工管理</a>
3.將list放在emp文件夾下
4.編寫處理請求的controller
@Controller
public class EmployeeController {
@Autowired
EmployeeDao employeeDao;
//查詢所有員工,返回列表頁面
@GetMapping("/emps")
public String list(Model model){
Collection<Employee> employees = employeeDao.getAll();
//將結果放在請求中
model.addAttribute("emps",employees);
return "emp/list";
}
}
我們啓動項目,測試一下看是否能夠跳轉,測試OK!我們只需要將數據渲染進去即可!
但是發現一個問題,側邊欄和頂部都相同,我們是不是應該將它抽取出來呢?
Thymeleaf 公共頁面元素抽取
1.抽取公共片段 th:fragment 定義模板名
2.引入公共片段 th:insert 插入模板名
我們來抽取一下,使用list列表做演示!我們要抽取頭部,nav標籤
我們在dashboard中將nav部分定義一個模板名;
<nav class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0" th:fragment="topbar" >
<!--後臺主頁顯示登錄用戶的信息-->
<a class="navbar-brand col-sm-3 col-md-2 mr-0" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">[[${session.loginUser}]]</a>
<input class="form-control form-control-dark w-100" type="text" placeholder="Search" aria-label="Search">
<ul class="navbar-nav px-3">
<li class="nav-item text-nowrap">
<a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">Sign out</a>
</li>
</ul>
</nav>
然後我們在list頁面中去引入,可以刪掉原來的nav
<!--引入抽取的topbar-->
<!--模板名 : 會使用thymeleaf的前後綴配置規則進行解析
使用~{模板::標籤名}-->
<div th:insert="~{dashboard::topbar}"></div>
效果:可以看到已經成功加載過來了!
除了使用insert插入,還可以使用replace替換,或者include包含,三種方式會有一些小區別,可以見名知義;
我們使用replace替換,可以解決div多餘的問題,可以查看thymeleaf的文檔學習
側邊欄也是同理,當做練手,可以也同步一下!
保證這一步做完!
我們發現一個小問題,側邊欄激活的問題,它總是激活第一個;按理來說,這應該是動態的纔對!
爲了重用更清晰,我們建立一個commons文件夾,專門存放公共頁面;
我們去頁面中引入一下
<div th:replace="~{commons/bar::topbar}"></div>
<div th:replace="~{commons/bar::sitebar}"></div>
我們先測試一下,保證所有的頁面沒有出問題!ok!
我們來解決我們側邊欄激活問題!
1.將首頁的超鏈接地址改到項目中
2.我們在a標籤中加一個判斷,使用class改變標籤的值;
<a class="nav-link active" th:class="${activeUrl=='main.html'?'nav-link active':'nav-link'}" href="#" th:href="@{/main.html}">
其餘同理,判斷請求攜帶的參數,進行激活測試
3.修改請求鏈接
其餘要用都是同理。我們刷新頁面,去測試一下,OK,動態激活搞定!
現在我們來遍歷我們的員工信息!順便美化一些頁面,增加添加,修改,刪除的按鈕
<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
<!--添加員工按鈕-->
<h2> <button class="btn btn-sm btn-success">添加員工</button></h2>
<div class="table-responsive">
<table class="table table-striped table-sm">
<thead>
<tr>
<th>id</th>
<th>lastName</th>
<th>email</th>
<th>gender</th>
<th>department</th>
<th>birth</th>
<!--我們還可以在顯示的時候帶一些操作按鈕-->
<th>操作</th>
</tr>
</thead>
<tbody>
<tr th:each="emp:${emps}">
<td th:text="${emp.id}"></td>
<td>[[${emp.lastName}]]</td>
<td th:text="${emp.email}"></td>
<td th:text="${emp.gender==0?'女':'男'}"></td>
<td th:text="${emp.department.departmentName}"></td>
<!--<td th:text="${emp.birth}"></td>-->
<!--使用時間格式化工具-->
<td th:text="${#dates.format(emp.birth,'yyyy-MM-dd HH:mm')}"></td>
<!--操作-->
<td>
<button class="btn btn-sm btn-primary">編輯</button>
<button class="btn btn-sm btn-danger">刪除</button>
</td>
</tr>
</tr>
</tbody>
</table>
</div>
</main>
OK,顯示全部員工OK!
添加員工信息
- 將添加員工信息改爲超鏈接
添加員工
2.編寫對應的controller
//to員工添加頁面
@GetMapping("/emp")
public String toAddPage(){
return "emp/add";
}
3.添加前端頁面;複製list頁面,修改即可
bootstrap官網文檔 : https://v4.bootcss.com/docs/4.0/components/forms/ , 我們去可以裏面找自己喜歡的樣式!
我這裏給大家提供了編輯好的
<form>
<div class="form-group">
<label>LastName</label>
<input type="text" class="form-control" placeholder="kuangshen">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" class="form-control" placeholder="[email protected]">
</div>
<div class="form-group">
<label>Gender</label><br/>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" value="1">
<label class="form-check-label">男</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" value="0">
<label class="form-check-label">女</label>
</div>
</div>
<div class="form-group">
<label>department</label>
<select class="form-control">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</div>
<div class="form-group">
<label>Birth</label>
<input type="text" class="form-control" placeholder="kuangstudy">
</div>
<button type="submit" class="btn btn-primary">添加</button>
</form>
4.部門信息下拉框應該選擇的是我們提供的數據,所以我們要修改一下前端和後端
controller
//to員工添加頁面
@GetMapping("/emp")
public String toAddPage(Model model){
//查出所有的部門,提供選擇
Collection<Department> departments = departmentDao.getDepartments();
model.addAttribute("departments",departments);
return "emp/add";
}
前端
<div class="form-group">
<label>department</label>
<!--提交的是部門的ID-->
<select class="form-control">
<option th:each="dept:${departments}" th:text="${dept.departmentName}" th:value="${dept.id}">1</option>
</select>
</div>
OK,修改了controller,重啓項目測試!
我們來具體實現添加功能;
1.修改add頁面form表單提交地址和方式
<form th:action="@{/emp}" method="post">
2.編寫controller;
//員工添加功能,使用post接收
@PostMapping("/emp")
public String addEmp(){
//回到員工列表頁面,可以使用redirect或者forward,就不會被視圖解析器解析
return "redirect:/emps";
}
前端填寫數據,注意時間問題
點擊提交,後臺輸出正常!頁面跳轉及數據顯示正常!OK!
那我們將時間換一個格式提交
提交發現頁面出現了400錯誤!
生日我們提交的是一個日期 , 我們第一次使用的 / 正常提交成功了,後面使用 - 就錯誤了,所以這裏面應該存在一個日期格式化的問題;
SpringMVC會將頁面提交的值轉換爲指定的類型,默認日期是按照 / 的方式提交 ; 比如將2019/01/01 轉換爲一個date對象。
這個在配置類中,所以我們可以自定義的去修改這個時間格式化問題,我們在我們的配置文件中修改一下;
spring.mvc.date-format=yyyy-MM-dd
這樣的話,我們現在就支持 - 的格式了,但是又不支持 / 了 , 2333吧
測試OK!
員工修改功能
我們要實現員工修改功能,需要實現兩步;
- 點擊修改按鈕,去到編輯頁面,我們可以直接使用添加員工的頁面實現
2.顯示原數據,修改完畢後跳回列表頁面!
我們去實現一下:首先修改跳轉鏈接的位置;
<a class="btn btn-sm btn-primary" th:href="@{/emp/}+${emp.id}">編輯</a>
編寫對應的controller
//to員工修改頁面
@GetMapping("/emp/{id}")
public String toUpdateEmp(@PathVariable("id") Integer id,Model model){
//根據id查出來員工
Employee employee = employeeDao.get(id);
//將員工信息返回頁面
model.addAttribute("emp",employee);
//查出所有的部門,提供修改選擇
Collection<Department> departments = departmentDao.getDepartments();
model.addAttribute("departments",departments);
return "emp/update";
}
我們需要在這裏將add頁面複製一份,改爲update頁面;需要修改頁面,將我們後臺查詢數據回顯
<form th:action="@{/emp}" method="post">
<div class="form-group">
<label>LastName</label>
<input name="lastName" type="text" class="form-control" th:value="${emp.lastName}">
</div>
<div class="form-group">
<label>Email</label>
<input name="email" type="email" class="form-control" th:value="${emp.email}">
</div>
<div class="form-group">
<label>Gender</label><br/>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" value="1"
th:checked="${emp.gender==1}">
<label class="form-check-label">男</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" value="0"
th:checked="${emp.gender==0}">
<label class="form-check-label">女</label>
</div>
</div>
<div class="form-group">
<label>department</label>
<!--提交的是部門的ID-->
<select class="form-control" name="department.id">
<option th:selected="${dept.id == emp.department.id}" th:each="dept:${departments}"
th:text="${dept.departmentName}" th:value="${dept.id}">1
</option>
</select>
</div>
<div class="form-group">
<label>Birth</label>
<input name="birth" type="text" class="form-control" th:value="${emp.birth}">
</div>
<button type="submit" class="btn btn-primary">修改</button>
</form>
測試OK!
發現我們的日期顯示不完美,可以使用日期工具,進行日期的格式化!
<input name="birth" type="text" class="form-control" th:value="${#dates.format(emp.birth,'yyyy-MM-dd HH:mm')}">
數據回顯OK,我們繼續完成數據修改問題!
修改表單提交的地址:
<form th:action="@{/updateEmp}" method="post">
編寫對應的controller
@PostMapping("/updateEmp")
public String updateEmp(Employee employee){
employeeDao.save(employee);
//回到員工列表頁面
return "redirect:/emps";
}
發現頁面提交的沒有id;我們在前端加一個隱藏域,提交id;
<input name="id" type="hidden" class="form-control" th:value="${emp.id}">
重啓,修改信息測試OK!
定製錯誤頁面
我們只需要在模板目錄下添加一個error文件夾,文件夾中存放我們相應的錯誤頁面,比如404.html 或者 4xx.html 等等,SpringBoot就會幫我們自動使用了!