5、SpringBoot:员工管理系统页面(仅供学习)

    科技2022-07-11  101

    文章目录

    1、首页实现2、国际化2.1、在resource下新建一个i18n目录(表示国际化)2.2、将i18n配置到application.properties中2.3、编写国际化解析器2.4、 将国际化解析器配置到Bean容器中 3、实现登录功能3.1、修改表单的active为controller里边的路径(RequestMapping)3.2、加入name属性,便于后台获取值,进行判断3.3、编写controller层业务3.4、加入错误信息提示,如果用户名或密码错误则输出提示3.5、登录之后路径会显示用户名,密码,需做修改 4、登录拦截器5、展示员工列表5.1、提取公共页面,新建Commons目录5.2、列表循环5.3、员工列表显示和点击高亮 6、添加员工信息6.1、在list页面增加一个添加员工的按钮6.2、添加一个add页面6.3、编写controller6.4、修改add页面部分代码6.4、controller层保存添加后的员工 7、修改员工信息7.1、新建一个update页面,修改list页面的编辑按钮,可以和后端进行交互7.2、编写controller层业务,需要跳转到update页面7.3、修改update页面内容7.4、修改日期的格式7.5、实现修改功能7.6、修改表单提交地址7.7、将id设置为隐藏域携带数据,方便去修改 8、删除员工信息8.1、修改删除按钮,可以重后端获取数据8.2、编写controller层业务 8、4049、注销

    1、首页实现

    导入thymeleaf模板引擎 <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> <version>2.3.4.RELEASE</version> </dependency> 在静态页面导入thymeleaf约束 xmlns:th="http://www.thymeleaf.org" 将链接使用thymeleaf语法替换

    关闭模板引擎的缓存 # 关闭模板引擎的缓存 spring.thymeleaf.cache=false 效果

    首页配置:需注意 == > 所有静态资源都需要使用thymeleaf来接管 :url ==> @{}

    2、国际化

    使用之前需要确保IDEA的所有编码都是UTF-8

    2.1、在resource下新建一个i18n目录(表示国际化)

    新建login.properties(默认的配置)再新建一个login_zh_CN.properties ==> 为中文配置新建之后两个文件会合并出一个新的文件,再次新建一个英文配置(login_en_US.properties)可手动添加,也可以右键添加

    目录:

    右键添加步骤:

    2.2、将i18n配置到application.properties中

    # 配置文件的真实位置 spring.messages.basename=i18n.login

    国际化使用的标签:#{}

    2.3、编写国际化解析器

    MyLocaleResolver

    public class MyLocaleResolver implements LocaleResolver { // 解析请求 @Override public Locale resolveLocale(HttpServletRequest request) { // 获取请求中的语言参数 String language = request.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) { } }

    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>

    2.4、 将国际化解析器配置到Bean容器中

    // 自定义的国际化组件注入到Bean中 @Bean public LocaleResolver localeResolver(){ return new MyLocaleResolver(); }

    效果:

    页面国际化

    我们需要配置i18n文件如果需要在项目中进行按钮自动切换,那么需要自定义一个组件LocaleResolver最后需要将自己写的组件配置到spring容器@Bean

    3、实现登录功能

    3.1、修改表单的active为controller里边的路径(RequestMapping)

    3.2、加入name属性,便于后台获取值,进行判断

    3.3、编写controller层业务

    @Controller public class LoginController { @RequestMapping("/user/login") public String login(@RequestParam("username") String username, @RequestParam("password") String password, Model model){ if ( "jack".equals(username) && "123".equals(password) ){ return "dashboard"; }else { // 返回错误信息 model.addAttribute("msg","用户名或密码错误"); return "index"; } } }

    3.4、加入错误信息提示,如果用户名或密码错误则输出提示

    th:if="${not #strings.isEmpty(msg)}" 为thymeleaf语法

    3.5、登录之后路径会显示用户名,密码,需做修改

    在配置中添加映射路径 registry.addViewController("/main.html").setViewName("dashboard"); 将controller层中的登录成功后的路径进行重定向

    再次登陆之后不在显示用户名和密码

    这里无论登不登录,都可以进入main页面,所以需要加入拦截器进行拦截

    4、登录拦截器

    在config下边新建一个LoginHandlerInterceptor去实现HandlerInterceptor接口 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; } } } 在controller里边获取session

    将拦截器配置到spring容器中 , 可设置放行和拦截地址 @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**").excludePathPatterns("/index.html","/","/user/login","/css/*","/js/*","/img/*"); }

    5、展示员工列表

    5.1、提取公共页面,新建Commons目录

    公共页面:

    <!-- 顶部导航栏 --> th:fragment="topbar" <!-- 侧边栏--> th:fragment="sidebar"

    子页面:

    <!-- 顶部导航栏 --> <div th:replace="~{commons/commons::topbar}"></div> <!-- 侧边栏--> <!-- 传递参数给组件--> <div th:replace="~{commons/commons::sidebar(active='list.html')}"></div>

    如果要传递参数,可以直接使用()传参,接收判断即可!

    增加编辑,删除按钮

    <td> <!-- 按钮,小按钮,按钮颜色 --> <button class="btn btn-sm btn-primary">编辑</button> <button class="btn btn-sm btn-danger">删除</button> </td>

    5.2、列表循环

    <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().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>

    需要对性别和日期做判断,使用三目表达式

    5.3、员工列表显示和点击高亮

    @Controller public class EmployeeController { @Autowired EmployeeDao employeeDao; @RequestMapping("/emp") public String employee(Model model){ Collection<Employee> employees = employeeDao.getAll(); model.addAttribute("emps",employees); return "emp/list"; } }

    点击高亮 需对active做出判断 效果展示

    学习视频:https://www.bilibili.com/video/BV1PE411i7CV?p=25

    6、添加员工信息

    6.1、在list页面增加一个添加员工的按钮

    <h2><a class="btn btn-sm btn-success" th:href="@{/emps}">添加员工</a></h2>

    效果:

    6.2、添加一个add页面

    <!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"> <form th:action="@{/emps}" method="post"> <div class="form-group"> <label>LastName</label> <input type="text" name="lastName" class="form-control" placeholder="海绵宝宝"> </div> <div class="form-group"> <label>Email</label> <input type="email" name="email" class="form-control" placeholder="1176244270@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:${department}" th:text="${dept.getDepartmentName()}" th:value="${dept.getId()}"></option> </select> </div> <div class="form-group"> <label>Birth</label> <input type="text" name="birth" class="form-control" placeholder="嘤嘤嘤"> </div> <button type="submit" class="btn btn-primary">添加</button> </form> </main> </div> </div> </body> </html>

    效果:

    6.3、编写controller

    // 点击增加员工,跳转页面 @GetMapping("/emps") public String toAddPage(Model model){ // 查出所有的部门信息 Collection<Department> department = departmentDao.getAllDepartment(); model.addAttribute("department",department); return "emp/add"; }

    6.4、修改add页面部分代码

    加入name属性,否则后台无法获取数据

    对部门进行遍历,根据部门id遍历,然后显示部门名称

    6.4、controller层保存添加后的员工

    @PostMapping("/emps") public String addEmp(Employee employee){ System.out.println(employee); // 保存员工信息 employeeDao.add(employee); return "redirect:/emp"; }

    效果

    注意

    这里输入时间时,系统默认为dd/MM/yyyy,如果需要"-"格式的,则需要在配置中修改

    spring.mvc.format.date=yyyy-MM-dd

    默认格式为:

    修改之后格式为:

    学习视频:https://www.bilibili.com/video/BV1PE411i7CV?p=26

    7、修改员工信息

    7.1、新建一个update页面,修改list页面的编辑按钮,可以和后端进行交互

    <!--${emp.getId()} 获取当前的id值--> <a class="btn btn-sm btn-primary" th:href="@{/emp/}+${emp.getId()}">编辑</a>

    7.2、编写controller层业务,需要跳转到update页面

    // 去员工的修改页面 @GetMapping("/emp/{id}") public String toUpdateEmployee(@PathVariable("id") Integer id,Model model){ // 根据id获取信息 Employee employeeById = employeeDao.getEmployeeById(id); model.addAttribute("emp",employeeById); // 查出所有的部门信息 Collection<Department> department = departmentDao.getAllDepartment(); model.addAttribute("department",department); return "emp/update"; }

    7.3、修改update页面内容

    注意

    取值需要使用:th:value="$()"标签由于性别使用的是0和1表示,所以性别需要做出判断,eg:使用th:checked="${}"标签部门需要显示显示选中的值,使用:th:selected="${}"

    7.4、修改日期的格式

    th:value="${#dates.format(emp.getBirth(),'yyyy-MM-dd HH:mm')}"

    7.5、实现修改功能

    @PostMapping("/updateEmp") public String updateEmp(Employee employee){ employeeDao.add(employee); return "redirect:/emp"; }

    7.6、修改表单提交地址

    这里点击修改会发现,并不是修改已有用户的信息,而是在增加员工信息,所以这里我们需要获取用户的id,根据id去修改用户的信息

    7.7、将id设置为隐藏域携带数据,方便去修改

    <input type="hidden" name="id" th:value="${emp.getId()}">

    8、删除员工信息

    8.1、修改删除按钮,可以重后端获取数据

    <a class="btn btn-sm btn-danger" th:href="@{/delete/}+${emp.getId()}">删除</a>

    8.2、编写controller层业务

    // 删除员工 @GetMapping("/delete/{id}") public String deleteEmp(@PathVariable("id") int id){ employeeDao.deleteEmployeeById(id); return "redirect:/emp"; }

    学习视频:https://www.bilibili.com/video/BV1PE411i7CV?p=27

    8、404

    在templates下面新建error目录,将404.html导入

    访问一个不存在的网页时效果

    9、注销

    在前端里边修改映射路径

    编写controller层业务 // 注销 @RequestMapping("/user/logout") public String logout(HttpSession session){ // 清除session session.invalidate(); return "redirect:/index.html"; }

    学习视频:https://www.bilibili.com/video/BV1PE411i7CV?p=28

    Processed: 0.010, SQL: 8