查看 pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com</groupId>
<artifactId>SpringBoot-05-EMS</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>SpringBoot-05-EMS</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
// 部门类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Department {
private Integer id;
private String departmentName;
}
// 员工类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Employee {
private Integer id;
private String lastName;
private String email;
private Integer gender;
private Department department;
private Date birth;
}
package com.springboot05ems.dao;
import com.springboot05ems.pojo.Department;
import org.springframework.stereotype.Repository;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* @author BoBooY
* @data 2022/9/4 19:57
*/
@Repository
public class DepartmentDao {
// 模拟数据库中的数据
private static Map<Integer, Department> departments = null;
static {
departments = new HashMap<Integer, Department>(); // 创建一个部门集合
departments.put(101,new Department(101,"运营部"));
departments.put(102,new Department(102,"策划部"));
departments.put(103,new Department(103,"法务部"));
departments.put(104,new Department(104,"开发部"));
departments.put(105,new Department(105,"宣传部"));
}
//获取所有部门的信息
public Collection<Department> getDepartments() {
return departments.values();
}
// 通过ID查询部门
public Department getDepartmentById(Integer id) {
return departments.get(id);
}
}
package com.springboot05ems.dao;
import com.springboot05ems.pojo.Department;
import com.springboot05ems.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* @author BoBooY
* @data 2022/9/4 20:25
*/
@Repository
public class EmployeeDao {
// 模拟数据库中的数据
private static Map<Integer, Employee> employees = null;
// 员工所属部门
@Autowired
private DepartmentDao departmentDao;
static {
employees = new HashMap<>(); // 创建一个部门
employees.put(1001, new Employee(1001, "BoBooY", "A1234567@qq.com", 1, new Department(1001, "运营部"), new Date()));
employees.put(1002, new Employee(1002, "BoBooY", "B1234567@qq.com", 0, new Department(1002, "策划部"), new Date()));
employees.put(1003, new Employee(1003, "BoBooY", "C1234567@qq.com", 1, new Department(1003, "法务部"), new Date()));
employees.put(1004, new Employee(1004, "BoBooY", "D1234567@qq.com", 0, new Department(1004, "开发部"), new Date()));
employees.put(1005, new Employee(1005, "BoBooY", "F1234567@qq.com", 1, new Department(1005, "宣传部"), new Date()));
}
// 增加员工,主键自增
private static Integer initid = 1006;
public void save(Employee employee){
if(employee.getId()==null){
employee.setId(initid++);
}
employee.setDepartment(departmentDao.getDepartmentById(employee.getDepartment().getId()));
employees.put(employee.getId(),employee);
}
// 查询全部员工信息
public Collection<Employee> getAll(){
return employees.values();
}
// 通过ID查询员工
public Employee getEmployee(Integer id){
return employees.get(id);
}
// 删除员工
public void delete(Integer id){
employees.remove(id);
}
}
静态资源链接:https://blog.csdn.net/qq_58233406/article/details/126838809?spm=1001.2014.3001.5502
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
方式一:编写一个Controller控制器
package com.springboot05ems.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @author BoBooY
* @data 2022/9/5 14:32
*/
@Controller
public class IndexController {
@RequestMapping({"/","/index.html"})
public String index() {
return "index";
}
}
成功访问首页
方式二:自己编写MVC的扩展配置
package com.springboot05ems.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author BoBooY
* @data 2022/9/5 17:03
*/
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("/index.html").setViewName("index");
}
}
<!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="@{/css/bootstrap.min.css}" rel="stylesheet">
<!-- Custom styles for this template -->
<link th:href="@{/css/signin.css}" rel="stylesheet">
</head>
<body class="text-center">
<form class="form-signin" action="dashboard.html">
<img class="mb-4" th:src="@{/img/bootstrap-solid.svg}" alt="" width="72" height="72">
<h1 class="h3 mb-3 font-weight-normal">Please sign in</h1>
<label class="sr-only">Username</label>
<input type="text" class="form-control" placeholder="Username" required="" autofocus="">
<label class="sr-only">Password</label>
<input type="password" class="form-control" placeholder="Password" required="">
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
<p class="mt-5 mb-3 text-muted">© 2022-2023</p>
<a class="btn btn-sm">中文</a>
<a class="btn btn-sm">English</a>
</form>
</body>
</html>
与上面示例修改方式一样,将src与href属性修改为模板规范格式,注意修改静态资源导入路径,本人的css,img,js在static目录下,删掉了asserts目录
login.btn=请登录
login.username=用户名
login.password=密码
login.remember=记住我
login.tip=请登录
login.btn=sign in
login.username=username
login.password=password
login.remember=remember me
login.tip=Please sign in
login.btn=请登录
login.username=用户名
login.password=密码
login.remember=记住我
login.tip=请登录
(springboot2.7.3)
spring.messages.basename=i18n.login
分析源码
如果我们想点击链接让个人的国际化资源生效,就需要让我们自己的Locale生效! 需要去自己写一个自己的LocaleResolver,可以在链接上携带区域信息。
配置国际化
<!-- Thymeleaf传参不用 ? 而是使用 (key=value) -->
<a class="btn btn-sm" th:href="@{/index.html(lang='zh_CH')}">中文</a>
<a class="btn btn-sm" th:href="@{/index.html(lang='en_US')}">English</a>
package com.springboot05ems.config;
import org.springframework.web.servlet.LocaleResolver;
import org.thymeleaf.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
/**
* @author BoBooY
* @data 2022/9/5 21:06
*/
public class MyLocaleResolver implements LocaleResolver {
@Override
public Locale resolveLocale(HttpServletRequest request) {
String lang = request.getParameter("lang");
Locale locale = Locale.getDefault();
//如果请求不为空
if(!StringUtils.isEmpty(lang)) {
//分割请求参数
String[] s = lang.split("_");
//国家,地区
locale = new Locale(s[0],s[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
}
}
@Bean
public LocaleResolver localeResolver() {
return new MyLocaleResolver();
}
主页面
点击English
点击中文
#关闭thymeleaf模板引擎的缓存
spring.thymeleaf.cache=false
【目前不连接数据库,输入任意用户名密码都可以登录】
package com.springboot05ems.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.thymeleaf.util.StringUtils;
import javax.servlet.http.HttpSession;
/**
* @author BoBooY
* @data 2022/9/6 11:52
*/
@Controller
public class LoginController {
@PostMapping("/user/login")
public String login(@RequestParam("username") String username, @RequestParam("password") String password, Model model, HttpSession session) {
//任意用户名和123密码即可登录
if(!StringUtils.isEmpty(username) && password.equals("123")) {
//登录注册session
session.setAttribute("loginUser",username);
return "dashboard"; //跳转首页
} else {
//登录失败!存放错误信息
model.addAttribute("msg","用户名或密码错误!");
return "index";
}
}
}
为了符合开发规范,登陆成功后应重定向到主页面
return "redirect:/main.html"; //跳转首页
registry.addViewController("/main.html").setViewName("dashboard");
package com.springboot05ems.config;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* @author BoBooY
* @data 2022/9/6 15:40
*/
public class LoginHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
if(session.getAttribute("loginUser") == null) {
//未登录,返回首页,并传入信息
request.setAttribute("msg","没有权限,请先登录!");
request.getRequestDispatcher("/index.html").forward(request,response);
return false;
} else {
//登录了,放行
return true;
}
}
}
//注册拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
.excludePathPatterns("/","/index.html","/user/login","/css/**","/img/**","/js/**");
}
[[${session.loginUser}]]
<li class="nav-item">
<a class="nav-link" th:href="@{/emps}">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-users">
<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path>
<circle cx="9" cy="7" r="4"></circle>
<path d="M23 21v-2a4 4 0 0 0-3-3.87"></path>
<path d="M16 3.13a4 4 0 0 1 0 7.75"></path>
</svg>
员工管理
</a>
</li>
package com.springboot05ems.controller;
import com.springboot05ems.dao.EmployeeDao;
import com.springboot05ems.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Collection;
/**
* @author BoBooY
* @data 2022/9/6 18:38
*/
@Controller
public class EmployeeController {
@Autowired
private EmployeeDao employeeDao;
//跳转到list页面
@RequestMapping("/emps")
public String list(Model model) {
Collection<Employee> employees = employeeDao.getAll();
model.addAttribute("emps",employees);
return "emp/list";
}
}
Thymeleaf 公共页面元素抽取
步骤:
操作:
commons.html
(topbar 和 sidebar)templates
目录下新建一个commons
包,其中新建commons.html
用来放置公共页面代码。<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<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" th: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" th:href="@{/index.html}">退出</a>
</li>
</ul>
</nav>
<nav class="col-md-2 d-none d-md-block bg-light sidebar" th:fragment="sidebar">
<div class="sidebar-sticky">
<ul class="nav flex-column">
<li class="nav-item">
<a class="nav-link active" th:href="@{/main.html}">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-home">
<path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path>
<polyline points="9 22 9 12 15 12 15 22"></polyline>
</svg>
首页 <span class="sr-only">(current)</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" th:href="@{http://getbootstrap.com/docs/4.0/examples/dashboard/#}">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-file">
<path d="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"></path>
<polyline points="13 2 13 9 20 9"></polyline>
</svg>
Orders
</a>
</li>
<li class="nav-item">
<a class="nav-link" th:href="@{http://getbootstrap.com/docs/4.0/examples/dashboard/#}">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-shopping-cart">
<circle cx="9" cy="21" r="1"></circle>
<circle cx="20" cy="21" r="1"></circle>
<path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path>
</svg>
Products
</a>
</li>
<li class="nav-item">
<a class="nav-link" th:href="@{/emps}">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-users">
<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path>
<circle cx="9" cy="7" r="4"></circle>
<path d="M23 21v-2a4 4 0 0 0-3-3.87"></path>
<path d="M16 3.13a4 4 0 0 1 0 7.75"></path>
</svg>
员工管理
</a>
</li>
<li class="nav-item">
<a class="nav-link" th:href="@{http://getbootstrap.com/docs/4.0/examples/dashboard/#}">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-bar-chart-2">
<line x1="18" y1="20" x2="18" y2="10"></line>
<line x1="12" y1="20" x2="12" y2="4"></line>
<line x1="6" y1="20" x2="6" y2="14"></line>
</svg>
Reports
</a>
</li>
<li class="nav-item">
<a class="nav-link" th:href="@{http://getbootstrap.com/docs/4.0/examples/dashboard/#}">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-layers">
<polygon points="12 2 2 7 12 12 22 7 12 2"></polygon>
<polyline points="2 17 12 22 22 17"></polyline>
<polyline points="2 12 12 17 22 12"></polyline>
</svg>
Integrations
</a>
</li>
</ul>
<h6 class="sidebar-heading d-flex justify-content-between align-items-center px-3 mt-4 mb-1 text-muted">
<span>Saved reports</span>
<a class="d-flex align-items-center text-muted" th:href="@{http://getbootstrap.com/docs/4.0/examples/dashboard/#}">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-plus-circle"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="16"></line><line x1="8" y1="12" x2="16" y2="12"></line></svg>
</a>
</h6>
<ul class="nav flex-column mb-2">
<li class="nav-item">
<a class="nav-link" th:href="@{http://getbootstrap.com/docs/4.0/examples/dashboard/#}">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-file-text">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
<polyline points="14 2 14 8 20 8"></polyline>
<line x1="16" y1="13" x2="8" y2="13"></line>
<line x1="16" y1="17" x2="8" y2="17"></line>
<polyline points="10 9 9 9 8 9"></polyline>
</svg>
Current month
</a>
</li>
<li class="nav-item">
<a class="nav-link" th:href="@{http://getbootstrap.com/docs/4.0/examples/dashboard/#}">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-file-text">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
<polyline points="14 2 14 8 20 8"></polyline>
<line x1="16" y1="13" x2="8" y2="13"></line>
<line x1="16" y1="17" x2="8" y2="17"></line>
<polyline points="10 9 9 9 8 9"></polyline>
</svg>
Last quarter
</a>
</li>
<li class="nav-item">
<a class="nav-link" th:href="@{http://getbootstrap.com/docs/4.0/examples/dashboard/#}">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-file-text">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
<polyline points="14 2 14 8 20 8"></polyline>
<line x1="16" y1="13" x2="8" y2="13"></line>
<line x1="16" y1="17" x2="8" y2="17"></line>
<polyline points="10 9 9 9 8 9"></polyline>
</svg>
Social engagement
</a>
</li>
<li class="nav-item">
<a class="nav-link" th:href="@{http://getbootstrap.com/docs/4.0/examples/dashboard/#}">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-file-text">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
<polyline points="14 2 14 8 20 8"></polyline>
<line x1="16" y1="13" x2="8" y2="13"></line>
<line x1="16" y1="17" x2="8" y2="17"></line>
<polyline points="10 9 9 9 8 9"></polyline>
</svg>
Year-end sale
</a>
</li>
</ul>
</div>
</nav>
</body>
</html>
list.html
和dashboard.html
中头部和侧边栏部分,使用抽取出来的模板代替<div th:replace="~{commons/commons::topbar}"></div>
<div th:replace="~{commons/commons::sidebar}"></div>
在页面中,使高亮的代码是class="nav-link active"
属性。
dashboard.html
的侧边栏标签传递参数active
为dashboard.html
。<!--侧边栏-->
<div th:replace="~{commons/commons::siderbar(active='dashboard.html')}"></div>
list.html
要传入的参数active
为list.html
<!--侧边栏-->
<div th:replace="~{commons/commons::siderbar(active='list.html')}"></div>
commons.html
相应标签部分利用thymeleaf
接收参数active
,利用三元运算符判断决定是否高亮。<a th:class="${active=='dashboard.html'?'nav-link active':'nav-link'}" th:href="@{/main.html}">
<a th:class="${active=='list.html'?'nav-link active':'nav-link'}" th:href="@{/emps}">
list.html
里面的数据,并修改时间日期格式,性别显示,并且添加两个操作按钮<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.getId()}"></td>
<td th:text="${emp.getLastName()}"></td>
<td th:text="${emp.getEmail()}"></td>
<td th:text="${emp.getGender()==0?'女':'男'}"></td>
<td th:text="${emp.getDepartment()}"></td>
<td th:text="${#dates.format(emp.getBirth(),'yyyy-MM-dd HH:mm')}"></td>
<td>
<a class="btn btn-sm btn-primary">编辑</a>
<a class="btn btn-sm btn-danger">删除</a>
</td>
</tr>
</tbody>
</table>
list.html
页面增添一个增加员工
按钮,点击该按钮时发起一个请求/add
。 <a class="btn btn-sm btn-success" th:href="@{/add}">添加员工</a>
EmployeeController
。//添加员工
@RequestMapping("/add")
public String add(Model model) {
return "emp/add";
}
templates/emp
创建添加员工页面add.html
<form>
<div class="form-group">
<label>LastName</label>
<input type="text" class="form-control" placeholder="BoBooY">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" class="form-control"
placeholder="1524368@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="BoBooY">
</div>
<button type="submit" class="btn btn-primary">添加</button>
</form>
//添加员工
@GetMapping("/add")
public String add(Model model) {
Collection<Department> departments = departmentDao.getDepartments();
model.addAttribute("depts",departments);
return "emp/add";
}
<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
<h2>员工管理</h2>
<form>
<div class="form-group">
<label>LastName</label>
<input type="text" name="lastName" class="form-control" placeholder="BoBooY">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" name="email" class="form-control" placeholder="12345678@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" name="department.id">
<option th:each="dept:${depts}" th:text="${dept.getDepartmentName()}" th:value="${dept.getId()}"> </option>
</select>
</div>
<div class="form-group">
<label>Birth</label>
<input type="text" class="form-control" name="birth" placeholder="birth:yyyy/MM/dd">
</div>
<button type="submit" class="btn btn-primary">添加</button>
</form>
</main>
form
表单添加action
属性和post
请求<form action="/addEmp" method="post"></form>
//添加员工
@PostMapping("/addEmp")
public String addEmp(Employee employee) {
System.out.println(employee);
employeeDao.save(employee);
return "redirect:/emps";
}
修改list页面代码
<td th:text="${emp.getDepartment().getDepartmentName()}"></td>
public static final String REDIRECT_URL_PREFIX = "redirect:";
public static final String FORWARD_URL_PREFIX = "forward:";
protected View createView(String viewName, Locale locale) throws Exception {
if (!this.alwaysProcessRedirectAndForward && !this.canHandle(viewName, locale)) {
vrlogger.trace("[THYMELEAF] View \"{}\" cannot be handled by ThymeleafViewResolver. Passing on to the next resolver in the chain.", viewName);
return null;
} else {
String forwardUrl;
if (viewName.startsWith("redirect:")) {
vrlogger.trace("[THYMELEAF] View \"{}\" is a redirect, and will not be handled directly by ThymeleafViewResolver.", viewName);
forwardUrl = viewName.substring("redirect:".length(), viewName.length());
RedirectView view = new RedirectView(forwardUrl, this.isRedirectContextRelative(), this.isRedirectHttp10Compatible());
return (View)this.getApplicationContext().getAutowireCapableBeanFactory().initializeBean(view, viewName);
} else if (viewName.startsWith("forward:")) {
vrlogger.trace("[THYMELEAF] View \"{}\" is a forward, and will not be handled directly by ThymeleafViewResolver.", viewName);
forwardUrl = viewName.substring("forward:".length(), viewName.length());
return new InternalResourceView(forwardUrl);
} else if (this.alwaysProcessRedirectAndForward && !this.canHandle(viewName, locale)) {
vrlogger.trace("[THYMELEAF] View \"{}\" cannot be handled by ThymeleafViewResolver. Passing on to the next resolver in the chain.", viewName);
return null;
} else {
vrlogger.trace("[THYMELEAF] View {} will be handled by ThymeleafViewResolver and a {} instance will be created for it", viewName, this.getViewClass().getSimpleName());
return this.loadView(viewName, locale);
}
}
}
@Bean
public FormattingConversionService mvcConversionService() {
WebConversionService conversionService = new WebConversionService(this.mvcProperties.getDateFormat());
this.addFormatters(conversionService);
return conversionService;
}
public String getDateFormat() {
return this.dateFormat;
}
# 日期格式化
spring.mvc.date-format=yyyy-MM-dd hh:mm
普通CRUD(uri来区分操作) | RestfulCRUD | |
---|---|---|
查询 | getEmp | emp–GET |
添加 | addEmp?xxx | emp–POST |
修改 | updateEmp?id=xxx&xxx=xx | emp/{id}–PUT |
删除 | deleteEmp?id=1 | emp/{id}—DELETE |
实验功能 | 请求URI | 请求方式 |
---|---|---|
查询所有员工 | emps | GET |
查询某个员工(来到修改页面) | emp/1 | GET |
来到添加页面 | emp | GET |
添加员工 | emp | POST |
来到修改页面(查出员工进行信息回显) | emp/1 | GET |
修改员工 | emp | PUT |
删除员工 | emp/1 | DELETE |
list.html
<a class="btn btn-sm btn-primary" th:href="@{/update/{id}(id=${emp.getId()})}">编辑</a>
add.html
到新建的update.html
中,并修改其中的标签属性,如下:<!DOCTYPE html>
<!-- saved from url=(0052)http://getbootstrap.com/docs/4.0/examples/dashboard/ -->
<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>Dashboard Template for Bootstrap</title>
<!-- Bootstrap core CSS -->
<link th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
<!-- Custom styles for this template -->
<link th:href="@{/css/dashboard.css}" rel="stylesheet">
<style type="text/css">
/* Chart.js */
@-webkit-keyframes chartjs-render-animation {
from {
opacity: 0.99
}
to {
opacity: 1
}
}
@keyframes chartjs-render-animation {
from {
opacity: 0.99
}
to {
opacity: 1
}
}
.chartjs-render-monitor {
-webkit-animation: chartjs-render-animation 0.001s;
animation: chartjs-render-animation 0.001s;
}
</style>
</head>
<body>
<div th:replace="~{commons/commons::topbar}"></div>
<div class="container-fluid">
<div class="row">
<div th:replace="~{commons/commons::sidebar(active='list.html')}"></div>
<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
<h2>修改员工</h2>
<form th:action="@{/updateEmp}" method="post">
<div class="form-group">
<label>LastName</label>
<input type="text" name="lastName" class="form-control" placeholder="BoBooY" th:value="${emp.getLastName()}">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" name="email" class="form-control" placeholder="12345678@qq.com" th:value="${emp.getEmail()}">
</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.getGender()==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.getGender()==0}">
<label class="form-check-label">女</label>
</div>
</div>
<div class="form-group">
<label>department</label>
<select class="form-control" name="department.id">
<option th:selected="${department.getId()==emp.department.getId()}"
th:each="department:${departments}" th:text="${department.getDepartmentName()}"
th:value="${department.getId()}">
</option>
</select>
</div>
<div class="form-group">
<label>Birth</label>
<input type="text" class="form-control" name="birth" placeholder="birth:yyyy-MM-dd" th:value="${emp.getBirth()}">
</div>
<button type="submit" class="btn btn-primary">修改</button>
</form>
</main>
</div>
</div>
${#dates.format(emp.getBirth(),'yyyy-MM-dd HH:mm')}
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script type="text/javascript" th:src="@{/js/jquery-3.2.1.slim.min.js}"></script>
<script type="text/javascript" th:src="@{/js/popper.min.js}"></script>
<script type="text/javascript" th:src="@{/js/bootstrap.min.js}"></script>
@{}
<!-- Icons -->
<script type="text/javascript" th:src="@{/js/feather.min.js}"></script>
<script>
feather.replace()
</script>
<!-- Graphs -->
<script type="text/javascript" th:src="@{/js/Chart.min.js}"></script>
<script>
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
datasets: [{
data: [15339, 21345, 18483, 24003, 23489, 24092, 12034],
lineTension: 0,
backgroundColor: 'transparent',
borderColor: '#007bff',
borderWidth: 4,
pointBackgroundColor: '#007bff'
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: false
}
}]
},
legend: {
display: false,
}
}
});
</script>
</body>
</html>
EmployeeController
中处理/update/{id}(id=${emp.getId()})
请求//跳转至编辑员工信息页面
@GetMapping ("/update/{id}")
public String update(@PathVariable("id") int id, Model model) {
System.out.println("进入了update");
Employee employee = employeeDao.getEmployee(id);
System.out.println(employee);
model.addAttribute("emp",employee);
Collection<Department> departments = departmentDao.getDepartments();
model.addAttribute("departments",departments);
return "/emp/update";
}
update.html
<input type="text" class="form-control" name="birth" placeholder="birth:yyyy-MM-dd" th:value="${#dates.format(emp.getBirth(),'yyyy-MM-dd HH:mm')}">
#修改日期格式
spring.mvc.format.date=yyyy-MM-dd HH:mm
EmployeeController
中添加updateEmp
方法//修改员工信息
@PostMapping("/updateEmp")
public String updateEmp(Employee employee) {
System.out.println(employee);
employeeDao.save(employee);
return "redirect:/emps";
}
list.html
,给a标签添加删除请求<a class="btn btn-sm btn-danger" th:href="@{/delete/{id}(id=${emp.getId()})}">删除</a>
EmployeeController
中添加delete
方法//删除员工信息
@GetMapping("/delete/{id}")
public String delete(@PathVariable("id") int id) {
employeeDao.delete(id);
return "redirect:/emps";
}
commons.html
<a class="nav-link" th:href="@{/logout}">退出</a>
logout
请求EmployeeController
中添加logout
方法//注销
@RequestMapping("/logout")
public String logout(HttpSession session) {
session.invalidate(); // 让当前的session失效,但是失效的时候浏览器会立刻创建一个新的session,所以调用原来session的getAttribute方法时候一定会抛出NullPointerException
return "redirect:/index.html";
}
ErrorMvcAutoConfiguration
这个配置类,这里面注入了几个很重要的 bean;错误处理步骤:
ErrorPageCustomizer
就会生效(定制错误的响应规则) @Bean
public ErrorPageCustomizer errorPageCustomizer(DispatcherServletPath
dispatcherServletPath) {
// 点进这个类
return new ErrorPageCustomizer(this.serverProperties,
dispatcherServletPath);
}
registerErrorPages
注册错误页面:@Override
public void registerErrorPages(ErrorPageRegistry errorPageRegistry) {
ErrorPage errorPage = new ErrorPage(
// 这里有个 getPath() 路径,我们点进去
this.dispatcherServletPath.getRelativePath(this.properties.getError().getPath()));
errorPageRegistry.addErrorPages(errorPage);
}
// getPath
public String getPath() {
return this.path;
}
// this.path;
@Value("${error.path:/error}")
private String path = "/error";
BasicErrorController
处理:@Controller
// 处理默认的 /error 请求
@RequestMapping("${server.error.path:${error.path:/error}}")
public class BasicErrorController extends AbstractErrorController {
}
// 产生html类型的数据,浏览器发送的请求会被这个方法处理
@RequestMapping(produces = MediaType.TEXT_HTML_VALUE)
public ModelAndView errorHtml(HttpServletRequest request,
HttpServletResponse response) {
HttpStatus status = getStatus(request);
Map<String, Object> model = Collections.unmodifiableMap(getErrorAttributes(request,
isIncludeStackTrace(request, MediaType.TEXT_HTML)));
response.setStatus(status.value());
// 去哪个页面拿错误页面呢?resolveErrorView 方法
ModelAndView modelAndView = resolveErrorView(request, response, status,model);
return (modelAndView != null) ? modelAndView : new ModelAndView("error",model);
}
// 返回 json 类型的数据,其他的客户端请求会被这个方法处理
@RequestMapping
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request)
{
HttpStatus status = getStatus(request);
if (status == HttpStatus.NO_CONTENT) {
return new ResponseEntity<>(status);
}
Map<String, Object> body = getErrorAttributes(request,
isIncludeStackTrace(request, MediaType.ALL));
return new ResponseEntity<>(body, status);
}
resolveErrorView
这个方法:protected ModelAndView resolveErrorView(HttpServletRequest request,
HttpServletResponse response,
HttpStatus status,
Map<String, Object> model) {
// 拿到所有的 errorViewResolvers 错误视图解析器
for (ErrorViewResolver resolver : this.errorViewResolvers) {
ModelAndView modelAndView = resolver.resolveErrorView(request,
status, model);
if (modelAndView != null) {
return modelAndView;
}
}
return null;
}
DefaultErrorViewResolver
默认的错误视图解析器 :public class DefaultErrorViewResolver implements ErrorViewResolver, Ordered
{
private static final Map<Series, String> SERIES_VIEWS;
static {
Map<Series, String> views = new EnumMap<>(Series.class);
views.put(Series.CLIENT_ERROR, "4xx"); // 客户端错误
views.put(Series.SERVER_ERROR, "5xx"); // 服务端错误
SERIES_VIEWS = Collections.unmodifiableMap(views);
}
// .....
@Override // HttpStatus 状态码
public ModelAndView resolveErrorView(HttpServletRequest request,
HttpStatus status, Map<String, Object> model) {
ModelAndView modelAndView = resolve(String.valueOf(status.value()),
model);
if (modelAndView == null &&
SERIES_VIEWS.containsKey(status.series())) {
// 通过状态码解析视图
modelAndView = resolve(SERIES_VIEWS.get(status.series()),
model);
}
return modelAndView;
}
// 去 error 路径下解析视图
private ModelAndView resolve(String viewName, Map<String, Object> model)
{
// 比如 error/404 error/500
String errorViewName = "error/" + viewName;
TemplateAvailabilityProvider provider =
this.templateAvailabilityProviders.getProvider(errorViewName,
this.applicationContext);
if (provider != null) {
return new ModelAndView(errorViewName, model);
}
return resolveResource(errorViewName, model);
}
}
总结
**定制错误页面,我们可以建立一个 error 目录,然后放入对应的错误码html文件! 比如:404.html 500.html **
<div th:replace="~{commons/commons::topbar}"></div>
<div th:replace="~{commons/commons::sidebar(active='list.html')}"></div>
解决方式:设置编码移除BOM
控制台报错
2022-09-12 15:49:39.658 WARN 18724 — [nio-8080-exec-6] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errorsField error in object ‘employee’ on field ‘birth’: rejected value [2022-10-12 15:49]; codes [typeMismatch.employee.birth,typeMismatch.birth,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [employee.birth,birth]; arguments []; default message [birth]]; default message [Failed to convert property value of type ‘java.lang.String’ to required type ‘java.util.Date’ for property ‘birth’; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Date] for value ‘2022-10-12 15:49’; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2022-10-12 15:49]]]
大概意思是:日期在转换时 格式错误 String类型无法转换成Util.Date类型
网页报错
解决问题
按照上图所示,后端配置的日期格式为:yyyy-MM-dd hh:mm
查看前端update页面设置的日期格式:yyyy-MM-dd HH:mm
由此可以发现 HH 和 hh格式不一样,才导致了错误
HH:24小时制 hh: 12小时制
补充
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm")
GitHub地址:https://github.com/BoBooY-GitHub/EMS_NoDatabase 百度网盘地址:https://blog.csdn.net/qq_58233406/article/details/126855928?spm=1001.2014.3001.5502