准备工作
导入静态资源,创建pojo包,编写dao层
员工表
//员工表
@Data
@NoArgsConstructor
public class Employee {
private Integer id;
private String lastName;
private String email;
private Integer gender; //性别 0 女, 1,男
private Department department;
private Date birth;
public Employee(Integer id, String lastName, String email, Integer gender, Department department) {
this.id = id;
this.lastName = lastName;
this.email = email;
this.gender = gender;
this.department = department;
this.birth = new Date();
}
}
部门表
//部门表
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Department {
private int id; //部门id
private String departmentName; //部门名字
}
模拟数据库
部门dao:
package com.chang.dao;
import com.kuang.pojo.Department;
import org.springframework.stereotype.Repository;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
//部门dao
@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);
}
}
员工dao
package com.chang.dao;
import com.kuang.pojo.Department;
import com.kuang.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
//员工dao
@Repository //被string托管
public class EmployeeDao {
//模拟数据库中的数据
private static Map<Integer, Employee> employees= null;
//员工所属的部门
@Autowired
private DepartmentDao departmentDao;
static {
employees = new HashMap<Integer,Employee>(); //创建一个部门表
employees.put(1001,new Employee( 1001,"AA","1622840727@qq.com",1,new Department(101,"教学部")));
employees.put(1002,new Employee( 1002,"BB","2622840727@qq.com",0,new Department(102,"市场部")));
employees.put(1003,new Employee( 1003,"CC","4622840727@qq.com",1,new Department(103,"教研部")));
employees.put(1004,new Employee( 1004,"DD","5628440727@qq.com",0,new Department(104,"运营部")));
employees.put(1005,new Employee( 1005,"FF","6022840727@qq.com",1,new Department(105,"后勤部")));
}
//主键自增
private static Integer ininId = 1006;
//增加一个员工
public void save(Employee employee){
if(employee.getId() == null){
employee.setId(ininId++);
}
employee.setDepartment(departmentDao.getDepartmentById(employee.getDepartment().getId()));
employees.put(employee.getId(),employee);
}
//查询全部的员工
public Collection<Employee>getALL(){
return employees.values();
}
//通过id查询员工
public Employee getEmployeeById(Integer id){
return employees.get(id);
}
//删除一个员通过id
public void delete(Integer id){
employees.remove(id);
}
}
首页实现
引入Thymeleaf
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
编写MyMvcConfig
@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");
}
所有的静态资源都需要使用thymeleaf接管:@{}
# 关闭模板引擎的缓存
spring.thymeleaf.cache=false
server.servlet.context-path=/chang
国际化:
在IDEA中统一设置properties的编码
在resources资源文件下新建一个i18n目录,存放国际化配置文件;建立一个login.properties文件,还有一个login_zh_CN.properties;
配置这个messages的路径
spring.messages.basename=i18n.login
index.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="@{/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" th:action="@{/user/login}">
<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}">Please sign in</h1>
<!--如果msg的值为空,则不显示消息-->
<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
<label class="sr-only" th:text="#{login.username}">Username</label>
<input type="text" name="username" class="form-control" th:placeholder="#{login.username}" required="" autofocus="">
<label class="sr-only" th:text="#{login.password}">Password</label>
<input type="password" name="password" class="form-control" 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>
根据按钮自动切换中文英文
在Spring中有一个国际化的Locale (区域信息对象);里面有一个叫做LocaleResolver (获取区域信息对象)的解析器!
编写一个处理的组件类
package com.chang.component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
//可以在链接上携带区域信息
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 httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
}
}
让我们的区域化信息能够生效,在我们自己的MvcConofig下添加bean;
@Bean
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}
登陆功能实现
@Controller
public class loginController {
@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:/index.html";
}
}
登陆拦截器
在LoginController添加serssion
session.setAttribute("loginUser",username);
自定义一个拦截器
public class LoginHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//登陆成功后,应该有用户的session
Object loginUser = request.getSession().getAttribute("loginUser");
if(loginUser==null){
//没有登陆
request.setAttribute("msg","没有权限,请先登录");
request.getRequestDispatcher("index.html").forward(request,response);
return false;
}else{
return true;
}
}
}
将拦截器注册到我们的SpringMVC配置类
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 注册拦截器,及拦截请求和要剔除哪些请求!
// 我们还需要过滤静态资源文件,否则样式显示不出来
registry.addInterceptor(new LoginHandlerInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/index.html","/user/login","/","/css/*","/img/**","/js/**");
}
在后台主页,获取用户登录的信息
<!--后台主页显示登录用户的信息-->
[[${session.loginUser}]] <!--$取EL表达式-->
展示员工列表
将首页的侧边栏Customers改为员工管理,a链接添加请求
<a class="nav-link" th:href="@{/emps}">员工管理</a>
编写处理请求的controller
//员工列表
@Controller
public class EmployeeController {
@Autowired
EmployeeDao employeeDao;
@RequestMapping("/emps")
public String list(Model model){
Collection<Employee> employees = employeeDao.getALL();
model.addAttribute("emps",employees);
return "emp/list";
}
}
公共页面元素抽取
1、抽取公共片段 th:fragment 定义模板名
2、引入公共片段 th:insert 插入模板名
建立一个commons文件夹,专门存放公共页面,需要的时候直接引用;
<!-- 顶部导航栏-->
<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" th:href="@{/user/logout}">注销</a>
</li>
</ul>
</nav>
<!--顶部导航栏-->
<div th:replace="~{commons/commons::topbar}"></div>
<!--侧边栏-->
<div th:replace="~{commons/commons::sidebar}"></div>
基本替换语法:
遍历我们的员工信息
<thead>
<tr>
<th>id</th>
<th>lastName</th>
<th>email</th>
<th>gender</th>
<th>department</th>
<th>birth</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.department.getDepartmentName()}"></td>
<td th:text="${#dates.format(emp.getBirth(),'yyyy-MM-dd HH:mm:ss')}"></td>
<td>
<button class="btn btn-sm btn-primary">编辑</button>
<button class="btn btn-sm btn-danger">删除</button>
</td>
</tr>
</tbody>
主要步骤:
增加员工信息
编写controller;
//员工添加功能
//接收前端传递的参数,自动封装成为对象[要求前端传递的参数名,和属性名一致]
@PostMapping ("/emp")
public String addEmp(Employee employee){
//保存员工的信息
System.out.println(employee);
employeeDao.save(employee);
// 回到员工列表页面,可以使用redirect或者forward,就不会被视图解析器解析
return "redirect:/emps";
}
修改add页面form表单提交地址和方式
<form th:action="@{/emp}" method="post"> 1
自定义的去修改这个时间格式化问题
spring.mvc.date-format=yyyy-MM-dd
修改员工信息
取员工修改页面:
//去员工的修改页面
@GetMapping("/emp/{id}")
public String toUpdateEmp(@PathVariable("id")Integer id,Model model){
//1.查出俩原来的数据
Employee employee = employeeDao.getEmployeeById(id);
model.addAttribute("emp",employee);
//查询所有部门的信息
Collection<Department> departments = departmentDao.getDepartments();
model.addAttribute("departments",departments);
return "emp/update";
}
@PostMapping("/updateEmp")
public String updateEmp(Employee employee){
employeeDao.save(employee);
return "redirect:/emps";
}
编写update页面
<form th:action="@{/emp}" method="post" >
<input type="hidden" name="id" th:value="${emp.getId()}">
<div class="form-group" ><label>LastName</label>
<input th:value="${emp.getLastName()}" class="form-control" placeholder="kuangshen" type="text" name="lastName">
</div>
<div class="form-group" ><label>Email</label>
<input th:value="${emp.getEmail()}" class="form-control" placeholder="24736743@qq.com" type="email" name="email">
</div>
<div class="form-group"><label>Gender</label><br/>
<div class="form-check form-check-inline">
<input th:checked="${emp.getGender()==1}" class="form-check-input" name="gender" type="radio" value="1">
<label class="form-check-label">男</label>
</div>
<div class="form-check form-check-inline">
<input th:checked="${emp.getGender()==0}" class="form-check-input" name="gender" type="radio" 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:selected="${dept.id==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:value="${#dates.format(emp.birth,'yyyy-MM-dd HH:mm')}" class="form-control" placeholder="2021-02-02" type="text" name="birth">
</div>
<button class="btn btn-primary" type="submit">修改</button>
</form>
删除及404处理
编写Controller
@GetMapping("/delemp/{id}")
public String deleteEmp(@PathVariable("id")int id){
employeeDao.delete(id);
return "redirect:/emps";
}
list页面,编写提交地址
<a class="btn btn-sm btn-danger" th:href="@{/delEmp/}+${emp.getId()}">删除</a>
404及注销
在模板目录下添加一个error文件夹,文件夹中存放我们相应的错误页面
@RequestMapping("/user/logout")
public String logout(HttpSession session){
session.invalidate();
return "redirect:/index.html";
}