SpringBoot-简单项目-09

1.进行项目的准备

  1. 创建好Employee类和Department类在pojo中
public class Employee {
    private Integer id;
    private String lastName;
    private String email;
    private Integer gender;

    private Department department;
    private Date birth;
//有参无参,getset,tostring方法
}
public class Department {
    private Integer id;
    private String departmentName;
//有参无参,getset,tostring方法
}
  1. 准备好数据,使用的是Map模拟数据库中的数据,以及准备好方法
    EmployeeDao(接口层)
@Repository
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","1321321@qq.com",1,new Department(101,"开发部")));
        employees.put(1002,new Employee(1002,"BB","1320320@qq.com",0,new Department(102,"市场部")));
        employees.put(1003,new Employee(1003,"CC","1320991@qq.com",1,new Department(103,"教研部")));
        employees.put(1004,new Employee(1004,"DD","1303219@qq.com",0,new Department(104,"运营部")));
        employees.put(1005,new Employee(1005,"EE","1321020@qq.com",1,new Department(105,"后勤部")));
    }
    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();
    }
    public Employee getEmployeeById(Integer id){
        return employees.get(id);
    }
    public void delete(Integer id){
        employees.remove(id);
    }
}

DepartmentDao

//部门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);
   }
}
  1. 准备好模板,可以在bootstrap或找其他的模板

  2. 页面放在templates下,css js img 等放在static下

  3. 修改html页面,使其符合Thymelea模板规范

    1. 在url路径下增加th:然后修改url路径为@{}格式
  4. 添加无业务逻辑跳转,创建MyMvcConfig

@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/index.html").setViewName("index");
    }
}

2. 项目国际化

  1. 在resources下创建i18n的文件夹,并创建login.proterties文件和login_zh_CN.properties文件和login_en_US.properties文件
  2. 在内部写入配置
login.password=password
login.tip=Please sign in
login.username=username
------------------------
login.password=密码
login.tip=请登录
login.username=用户名
------------------------
login.password=password
login.tip=Please sign in
login.username=username
------------------------
  1. 在核心配置文件application.yaml中加入
spring:
  messages:
    basename: i18n.login
  1. 在config包内创建类(MyLocaleResolver),实现localerslove接口,重写方法,解析请求

public class MyLocaleResolver implements LocaleResolver {
    //解析请求
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        String language = request.getParameter(String.valueOf('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) {
    }
}
  1. 在MyMvcConfig中配置Bean
   @Bean
    public LocaleResolver localeResolver(){
        return new MyLocaleResolver();
    }
  1. 在页面的中英文切换按钮板顶请求,并修改文字元素为thymeleaf格式
<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>

3. 项目:登陆+拦截器

  1. 修改页面的form的action请求为th:action并修改表单的提交请求

  2. 新建一个表单的提交跳转地址LoginController

@Controller
public class LoginController {
    @RequestMapping("/user/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        Model model){
        if (!StringUtils.isEmpty(username)&&"123456".equals(password)){
            return "redirect:/main.html";
        }else{
            model.addAttribute("msg","用户名或者密码错误");
            return "index";
        }
    }
}
  1. 增加提示用户名和密码错误的标签在index页面中
    <p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>

  2. 在MyMvcConfig中添加映射

 registry.addViewController("/main.html").setViewName("dashboard");
  1. 还需要配置拦截器(如果不配置的话用户可以跳过验证阶段直接输入/main.html页面跳转至里面)在config中创建连接器LoginHandlerInterceptor然后实现接口HandlerIntercrptor重写那三个方法之后只需要之前拦截
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;
        }
    }
}
  1. 在LoginController中添加
@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";
        }
    }
}
  1. 配置到Bean中注册重写addInterceptors(MyMvcConfig)
@Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginHandlerInterceptor()).
                addPathPatterns("/**").
                excludePathPatterns("index.html","/","/user/login");
    }
  1. 此处如果直接访问localhost:8080/sli/mian.html会直接报500错误,检查之后发现配置到Bean的文件资源过滤的时候少写一个斜杠,就是上述代码中的index.html,谨记!

4. 项目展示员工表(大量涉及前端,不详解)

  1. 首先做代码的复用,也就是取下来首页的头边框和侧边框到单独的一个html页面中,新建一个commons的文件夹在templates下,并新建一个commons.html用于存放以下的代码其中做了点击事件的绑定,所以需要给list.html页面和dashboard.html页面添加第二步中的xxx.html代表跳转的页面(此处可以新建文件夹emp用来存放其他的页面例如list以及add和其他操作的页面)
点击查看代码
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<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/#">注销</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 th:class="${active=='main.html'?'nav-link active':'nav-link'}" th:href="@{/index.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" 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" 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 th:class="${active=='list.html'?'nav-link active':'nav-link'}" th:href="@{/emps}">
                    员工管理
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" 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" 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" 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" 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" 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" 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" 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>
</html>

2. 在其他需要的页面引入`
`和`
`进行复用 3. 新建一个EmployeeController来处理请求数据 ```java 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";
}

}

4. 在页面中定义表格,将获取到的数据通过thymeleaf显示
```html
<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
             <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.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>
                </table>
            </div>
        </main>

5. 增加员工的实现

  1. 增加添加按钮在list页面的<h2><a class="btn btn-sm btn-success" th:href="@{/emp}">添加员工</a></h2>
  2. 在EmployeeController中添加如下代码实现添加员工页面的跳转
 @Autowired
    DepartmentDao departmentDao;
    @RequestMapping("/emp")
    public String toAddpage(Model model){
        //查出所有的部门信息
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("departments",departments);
        return "emp/add";
    }
  1. 在emp中新建add.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>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>

		<div class="sidebar-sticky">
			<ul class="nav flex-column">
				<li class="nav-item">
					<a class="nav-link active" 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-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>
						Dashboard <span class="sr-only">(current)</span>
					</a>
				</li>
				<li class="nav-item">
					<a class="nav-link" 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" 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}">
						员工管理
					</a>
				</li>
				<li class="nav-item">
					<a class="nav-link" 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" 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"
				   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" 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" 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" 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" 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>
		<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">

			
			<form th:action="@{/emp}" method="post">
				<div class="form-group">
					<lable>LastName</lable>
					<input name="lastName" type="text" class="form-control" placeholder="xxx">
				</div>
				<div class="form-group">
					<lable>Email</lable>
					<input name="email" type="email" class="form-control" placeholder="xxxxxxxx@xx.com">
				</div>
				<div class="form-group">
					<lable>Gender</lable>
					<div class="form-check form-check-inline">
						<input class="form-check-input" type="radio" name="gender" value="1">
						<lable class="form-check-label">男</lable>
					</div>
					<div class="form-check form-check-inline">
						<input class="form-check-input" type="radio" name="gender" value="0">
						<lable class="form-check-label">女</lable>
					</div>
				</div>
				<div class="form-group">
					<label>department</label>
					<select class="form-control" name="department.id">
						<option th:each="dept:${departments}" th:text="${dept.getDepartmentName()}"
								th:value="${dept.getId()}"></option>
					</select>
				</div>
				<div class="form-group"></div>
				<label>Birth</label>
				<input type="text" class="form-control" name="birth" placeholder="yyyy-MM-dd">
				<button type="submit" class="btn btn-primary">添加</button>
			</form>
			
			
		</main>
	</div>
</div>

<script type="text/javascript" src="asserts/js/jquery-3.2.1.slim.min.js"></script>
<script type="text/javascript" src="asserts/js/popper.min.js"></script>
<script type="text/javascript" src="asserts/js/bootstrap.min.js"></script>

<!-- Icons -->
<script type="text/javascript" src="asserts/js/feather.min.js"></script>
<script>
	feather.replace()
</script>

<!-- Graphs -->
<script type="text/javascript" src="asserts/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>
  • 以上不做过多的解释,具体就是修改了中间的form表单,由于部门显示的是数字,所以用多选框来遍历里面部门的名字
  1. 在EmployeeController中增加
@RequestMapping("/emp")
    public String toAddpage(Model model){
        //查出所有的部门信息
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("departments",departments);
        return "emp/add";
    }
  1. 点击按钮之后能把数据提交到后台需要在EmployeeController添加方法
 @PostMapping("/emp")
    public String addEmp(Employee employee){
        employeeDao.save(employee);
        return "redirect:/emps";
    }
  1. 如果需要提交的时间格式需要在application.yaml中添加
spring:
  mvc:
    format:
      date: yyyy-MM-dd

4. 修改员工的实现

  1. 首先给list.html的编辑按钮修改成a标签,然后增加跳转页面th:href="@{/emp/}+${emp.getId()}"
  2. 在EmployeeController中增加跳转到员工修改页面的方法,并在templates的emp页面中增加update.html(复制一份add页面即可)
//去员工的修改页面
    @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";
    }
  1. 在页面update.html中取出原来存放的数据,就是在这个页面中取出模拟表中的数据,并修改按钮名字为"修改"
<form th:action="@{/updateEmp}" method="post">
				<div class="form-group">
					<lable>LastName</lable>
					<input th:value="${emp.getLastName()}" name="lastName" type="text" class="form-control" placeholder="xxx">
				</div>
				<div class="form-group">
					<lable>Email</lable>
					<input th:value="${emp.getEmail()}" name="email" type="email" class="form-control" placeholder="xxxxxxxx@xx.com">
				</div>
				<div class="form-group">
					<lable>Gender</lable>
					<div class="form-check form-check-inline">
						<input th:checked="${emp.getGender()==1}" class="form-check-input" type="radio" name="gender" value="1">
						<lable th:checked="${emp.getGender()==0}" class="form-check-label">男</lable>
					</div>
					<div class="form-check form-check-inline">
						<input class="form-check-input" type="radio" name="gender" value="0">
						<lable class="form-check-label">女</lable>
					</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"></div>
				<label>Birth</label>
				<input th:value="${#dates.format(emp.getBirth,'yyyy-MM-dd')}" type="text" class="form-control" name="birth" placeholder="yyyy-MM-dd">

				<button type="submit" class="btn btn-primary">修改</button>
			</form>
  1. 测试发现能取出模拟表中的数据,但是点击修改之后会发现不能提交数据.所以在EmployeeController中增加方法
  @PostMapping("/updateEmp")
    //员工信息修改
    public String updateEmp(Employee employee){
        employeeDao.save(employee);
        return "redirect:/emps";
    }
  1. 这时候点击一次修改会默认增加一个员工,所以需要把id和隐藏域携带过来在update.html中增加
<input type="hidden" name="id" th:value="${emp.getId()}">
  1. 测试发现成功

5. 请自己实现删除以及404还有logout

提示:404只需要在templates中新建一个error文件夹,再将404.html放入即可

posted @ 2021-09-25 07:58  1_f  阅读(23)  评论(0)    收藏  举报