【狂神说Java】SpringBoot最新教程IDEA版通俗易懂20 ~ 28:员工管理系统
20、员工管理系统:准备工作
首先确定项目的结构:
从底层开始编写。
静态资源导入
(伪造)数据库
导入lombok,添加lombok依赖:
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
编写部门表
// 部门表
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Department {
private Integer id ;
private String departmentName ;
}
编写员工表
@Data
@NoArgsConstructor
public class Employee {
private Integer id ;
private String lastName ;
private String email ;
private Integer sex ; // 0女、1男
private Department department ;
private Date birth ; // Date类用于描述日期信息
// 定义有参构造,为了让birth内部生成
public Employee(Integer id, String lastName, String email, Integer sex, Department department) {
this.id = id;
this.lastName = lastName;
this.email = email;
this.sex = sex;
this.department = department;
this.birth = new Date();
}
}
编写Dao层
部门
@Repository
public class DepartmentDao {
// 初始化数据:模拟数据库中的数据
// 在初始化时加载,需要static;库需要map实现
private static Map<Integer, Department> departments = null ;
// 下面赋初始值
static {
departments = new HashMap<>() ; // 创建一个部门表,JDK1.8之后泛型可省略
departments.put(1701, new Department(1701, "Fintech Department")) ;
departments.put(1702, new Department(1702, "Administrative Department")) ;
departments.put(1703, new Department(1703, "Human Resources Department")) ;
departments.put(1704, new Department(1704, "Department of trade and Finance")) ;
departments.put(1705, new Department(1705, "Retail Business Department")) ;
}
/* 数据库的增删查改 */
// 获得所有部门信息
public Collection<Department> getDepartments() {
return departments.values() ;
}
// 通过部门id得到部门信息
public Department getDepartmentById(Integer id) {
return departments.get(id) ;
}
}
员工
@Repository
public class EmployeeDao {
// 初始化数据:模拟数据库中的数据
// 在初始化时加载,需要static;库需要map实现
private static Map<Integer, Employee> employees = null ;
// 首先员工有所属部门
@Autowired // 可以使用DepartmentDao了
private DepartmentDao departmentDao ; // 这个操作要求这两个Dao被@Repository ➡ 被Spring托管
// 下面赋初始值
static {
employees = new HashMap<>() ; // 创建一个部门表,JDK1.8之后泛型可省略
employees.put(13001, new Employee(13001, "Hathway", "aaaa@mail.com", 0, new Department(1704, "Department of trade and Finance"))) ;
employees.put(13002, new Employee(13002, "Dexter", "bbbb@mail.com", 1, new Department(1701, "Fintech Department"))) ;
employees.put(13003, new Employee(13003, "Nana", "dddd@mail.com", 0, new Department(1703, "Human Resources Department"))) ;
employees.put(13004, new Employee(13004, "Choco", "eeee@mail.com", 0, new Department(1705, "Retail Dusiness Department"))) ;
employees.put(13005, new Employee(13005, "Tataki", "ffff@mail.com", 1, new Department(1702, "Administrative Department"))) ;
// 因为static的原因,无法用departmentDao.getDepartmentById(Integer id)方法来获取部门
}
/* 增删查改 */
// 增加一个员工
private static Integer initId = 13006 ;
public void add(Employee employee) {
if (null == employee.getId()) {
employee.setId(initId++) ;
}
employee.setDepartment(departmentDao.getDepartmentById(employee.getDepartment().getId()));
employees.put(employee.getId(),employee) ;
}
// 获得所有员工信息
public Collection<Employee> getEmployees() {
return employees.values() ;
}
// 通过员工id得到员工信息
public Employee getEmployeeById(Integer id) {
return employees.get(id) ;
}
// 通过员工id删除员工
public void delete(Integer id) {
employees.remove(id) ;
}
}
21、员工管理系统:首页实现
以扩展mvc的方式实现首页:
- 在MyMvcConfig中:
// 使用WebMvcConfigurer可以来扩展SpringMVC的功能
// @EnableWebMvc这里不能使用,因为不需要接管SpringMVC
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// super.addViewControllers(registry);
// 浏览器发送 / 请求来到 index
registry.addViewController("/").setViewName("index");
// 浏览器发送 index.html 请求来到 index
registry.addViewController("/index.html").setViewName("index");
}
}
现在的问题是:为什么静态资源没有加载?
- 因为现在的模板引擎是Thymeleaf,需要改index.html为Thymeleaf支持。
<!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">
<!-- href="asserts/css/bootstrap.min.css 改为 th:href=@{/css/bootstrap.min.css} -->
<!-- Custom styles for this template -->
<link th:href="@{/css/signin.css}" rel="stylesheet">
<!-- href=asserts/css/signin.css 改为 th:href=@{/css/signin.css} -->
</head>
······
</html>
可以看到静态资源成功加载:
项目中其余html文件都要修改,不再赘述。
最终效果:
22、员工管理系统:国际化
首先,确定编码格式为utf-8。
所谓国际化就是可以切换多语言(中英切换)。
编写配置文件
新建如下所示三个配置文件,系统会把它们自动合并,然后可以使用IDEA提供的方便的Resource Bundle功能,同时编辑这三个文件:
在application.properties文件中添加:spring.messages.basename=i18n.login
,绑定配置文件的位置。
编辑index.html文件
<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" th:text="#{login.tip}"></h1>
<label class="sr-only" th:text="#{login.username}"></label>
<input type="text" class="form-control" th:placeholder="#{login.username}" required="" autofocus="">
<label class="sr-only" th:text="#{login.password}"></label>
<input type="password" class="form-control" th:placeholder="#{login.password}" required="">
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me" th:text="#{login.remember}">
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.enter}"></button>
<p class="mt-5 mb-3 text-muted">© 2017-2018</p>
<a class="btn btn-sm">中文</a>
<a class="btn btn-sm">English</a>
</form>
</body>
怎么能做到中英文切换呢?
编辑Index.html
<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>
编写demo.web.config.MyLocaleResolver
public class MyLocaleResolver implements LocaleResolver {
// 解析请求
@Override
public Locale resolveLocale(HttpServletRequest httpServletRequest) {
// 获取请求中的语言参数
String language = httpServletRequest.getParameter("l") ;
// 如果没有就使用默认
Locale locale = Locale.getDefault() ;
// 如果请求的链接携带了国际化参数
if (!StringUtils.isEmpty(language)) {
// zh_CN
String[] split = language.split("_");
// 国家,地区
locale = new Locale(split[0], split[1]) ;
}
return locale;
}
@Override
public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
}
}
把国际化组件MyLocaleResolver放到Bean里面:
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
······
// 这样自定义的国际化组件就生效了
@Bean
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}
}
运行:
23、员工管理系统:登录功能实现
编辑index.html,定义登录页面:
<body class="text-center">
<form class="form-signin" th:action="@{/user/login}">
<label class="sr-only" th:text="#{login.username}"></label>
<input type="text" class="form-control" name="username" th:placeholder="#{login.username}" required="" autofocus="">
<label class="sr-only" th:text="#{login.password}"></label>
<input type="password" class="form-control" name="password" th:placeholder="#{login.password}" required="">
</body>
编写LoginController
@Controller
public class LoginController {
@RequestMapping("/user/login")
// 注意这里一定不能用@ResponseBody
public String login(@RequestParam("username") String username,
@RequestParam("password") String password,
Model model){
// 编写具体业务
if (!StringUtils.isEmpty(username) && "123456".equals(password)) {
// 登陆成功
return "dashboard";
} else {
//登陆失败
model.addAttribute("msg","用户名或密码错误");
return "index";
}
}
}
在登录时如果出现错误怎么才能让页面弹出提示呢?
<body class="text-center">
<form class="form-signin" th:action="@{/user/login}">
<h1>······</h1>
<!-- 如果msg为空则不显示消息 -->
<p style="color:red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
</body>
成功登录,但是:
这显然是不符合要求的,修改MyMvcConfig:
@Override
public void addViewControllers(ViewControllerRegistry registry) {
······
registry.addViewController("/main.html").setViewName("dashboard");
}
这样可以直接访问http://localhost:8080/main.html
。
更好的做法是登录之后直接跳转到main.html:修改LoginController:
if (!StringUtils.isEmpty(username) && "123456".equals(password)) {
······
return "redirect:/main.html";
}
问题:这样修改之后,无论登陆与否,都能直接访问后台页面,需要设置登录拦截器。
24、员工管理系统:登录拦截器
编辑LoginHandlerInterceptor继承HandlerInterceptor接口:
public class LoginHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// return:true放行,false不放行
// 登录成功之后应该有用户的session
// session放在LoginController中
Object loginUser = request.getSession().getAttribute("loginUser") ;
if (loginUser == null) { // 没有登录
request.setAttribute("msg","请先登录"); // 显示信息
request.getRequestDispatcher("/index.html").forward(request,response) ; // 返回首页
return false ;
} else {
return true ;
}
}
}
在MyMvcConfig中注册拦截器:
// 注册拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 设置拦截哪些请求
registry.addInterceptor(new LoginHandlerInterceptor()).
addPathPatterns("/**").excludePathPatterns("/index.html","/","/user/login","/css/**","/js/**","/img/**");
//静态资源:*.css、*.js、*.img也不被拦截,为了登录失败时页面可以正常加载
}
为防止表单重复提交,在LoginController中添加功能:
// 编写具体业务
if (!StringUtils.isEmpty(username) && "123456".equals(password)) {
// 登录成功,防止表单重复提交,可以重定向到主页
session.setAttribute("loginUser",username);
return "redirect:/main.html";
}
编辑dashboard.html中的Company Name,让登陆用户名为Company Name:
<a class="navbar-brand col-sm-3 col-md-2 mr-0" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">[[${session.loginUser}]]</a>
查看效果:
25、员工管理系统:展示员工列表
编写EmployeeController:
- EmployeeDao类中已经定义好了所有的方法,这里直接使用(@Autowired)
@Controller
public class EmployeeController {
@Autowired
EmployeeDao employeeDao ;
@RequestMapping("/emps")
public String list(Model model) {
Collection<Employee> employees = employeeDao.getEmployees() ;
model.addAttribute("emps",employees) ;
return "emp/list" ;
}
}
在templates中创建一个文件夹commons,在其中编辑一个commons.html,作用是页面模板,其他页面通过插入commons.html中的设计的方式实现代码复用。
- 操作简单,只要把顶部导航栏和侧边栏代码剪切到commons.html,再在dashboard.html和list.html中替换(
th:replace="~{commons/commons::xxx}"
)。不附代码。
下面实现:选中时高亮功能。
使用条件判断句:
th:class="${active=='xxxx.html'?'nav-link active':'nav-link'}"
下面实现:员工表格式修改
要求:
- 显示员工信息
- 提供编辑选项
- 性别显示男女而非数字
- 日期格式为:年-月-日 时-分-秒
进入list.html
,修改:
26、员工管理系统:增加员工实现
按钮提交,跳转到添加页面
在emp文件夹中创建一个add.html,在EmployeeController中添加:
@GetMapping("/add")
public String toAddPage() {
return "emp/add" ;
}
添加员工成功
编辑add.html文件,点击添加员工时该页面,进行添加操作。
编辑EmployeeController文件,实现添加功能:
@GetMapping("/add") // 获取表单
public String toAddPage(Model model) {
// 查出所有部门的信息
Collection<Department> departments = departmentDao.getDepartments() ;
model.addAttribute("departments",departments) ;
return "emp/add" ;
}
返回员工列表页
编辑EmployeeController文件,实现返回:
@PostMapping("/add") // 提交表单
public String addEmp(Employee employee) {
// 添加操作
employeeDao.add(employee); // 调用底层业务方法保存员工信息
return "redirect:/emps" ; // 跳转回员工列表
}
}
注意:
- 这里新员工的birth在填写时我们要求的格式为yyyy-MM-dd,而默认格式是yyyy/MM/dd,所以要在applications.properties中进行修改:
spring.mvc.format.date=yyyy-MM-dd
27、员工管理系统:修改员工信息
首先编辑list.html,使页面中的编辑选项具有功能:
<a class="btn btn-sm btn-primary" th:href="@{/emp/}+${theemp.getId()}">修改</a>
注意这里是a标签,而不是button标签。
修改EmployeeController,使编辑跳转到update页面:
/** 跳转到员工的修改页面 */
@GetMapping("/emp/{id}")
public String toUpdateEmp(@PathVariable("id")Integer id, Model model) {
// 查出原来的数据
Employee employee = employeeDao.getEmployeeById(id) ;
model.addAttribute("emp",employee) ;
// 查出所有部门的信息
Collection<Department> departments = departmentDao.getDepartments() ;
model.addAttribute("departments",departments) ;
return "emp/update" ;
}
update.html和list.html在同一个文件夹(emp)下,直接复制list.html页面然后在此基础上进行修改:
<form th:action="@{/update}" method="post">
<div class="form-group">
<label>LastName</label>
<input th:value="${emp.getLastName()}" type="text" name="lastName" class="form-control" placeholder="用户名">
</div>
<div class="form-group">
<label>Email</label>
<input th:value="${emp.getEmail()}" type="email" name="email" class="form-control" placeholder="请输入正确的邮箱格式">
</div>
<div class="form-group">
<label>Sex</label><br>
<div class="form-check form-check-inline">
<input th:checked="${emp.getSex()==1}" class="form-check-input" type="radio" name="sex" value="1">
<label class="form-check-label">MALE</label>
</div>
<div class="form-check form-check-inline">
<input th:checked="${emp.getSex()==0}" class="form-check-input" type="radio" name="sex" value="0">
<label class="form-check-label">FEMALE</label>
</div>
</div>
<div class="form-group">
<label>Department</label>
<select class="form-control" name="department.id">
<option th:selected="${dept.getId()==emp.getDepartment().getId()}" th:each="dept:${departments}" th:text="${dept.getDepartmentName()}" th:value="${dept.getId()}"></option>
</select>
</div>
<div class="form-group">
<label>Birth</label>
<input th:selected="${emp.getBirth()}" type="text" name="birth" class="form-control" placeholder="yyyy-MM-dd">
</div>
<button type="submit" class="btn btn-primary">确定修改</button>
</form>
效果如下,这里生日格式有些问题,以后修改。
下一步要实现点击确认修改标签,成功提交修改后的表单。
/** 提交修改后的表单 */
@PostMapping("/update")
public String updateEmp(Employee employee) {
employeeDao.add(employee) ;
return "redirect:/emps" ;
}
修改日期格式,使提交时不报错:
<div class="form-group">
<label>Birth</label>
<input th:value="${#dates.format(emp.getBirth(),'yyyy-MM-dd')}" th:selected="${emp.getBirth()}" type="text" name="birth" class="form-control" placeholder="yyyy-MM-dd">
</div>
这样就实现了修改功能:
但是问题来了,修改后的员工信息应该回到自己的ID对应的栏,而不是新建一栏,下面进行修正:
编辑update.html:
<form th:action="@{/update}" method="post">
<input type="hidden" name="id" th:value="${emp.getId()}">
······
28、员工管理系统:删除及404处理
在list.html中为删除标签添加功能:
<a class="btn btn-sm btn-danger" th:href="@{/delemp/}+${theemp.getId()}">删除</a>
编辑EmployeeController:
/** 删除员工 */
@GetMapping("/delemp/{id}")
public String toDeleteEmp(@PathVariable("id")Integer id) {
employeeDao.delete(id); ;
return "redirect:/emps" ;
}
实现效果:点击删除按钮之后还是直接跳转到这个页面,员工信息成功删除。
404处理:
springboot中404处理很方便:
- 在templates下新建error文件夹,里面放入需要处理的错误,比如404.html,访问错误的端口时就会自动进行404处理。
最后的操作:注销
编辑commons.html。在头部导航栏位置:
<li class="nav-item text-nowrap">
<a class="nav-link" th:href="@{/user/logout}">注销</a>
</li>
编辑LoginController:
@RequestMapping("/user/logout")
public String logout(HttpSession session) {
session.invalidate() ;
return "redirect:/index.html" ;
}
点击注销,会自动跳转到登陆页面。