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="24736743@qq.com">
</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就会帮我们自动使用了!