狂神说SpringBoot员工管理系统

一、springboot员工管理系统(没数据库的版本)

1.导入静态资源

链接https://pan.baidu.com/s/1Pwy21L8G3Rid0BsC67p0OQ
提取码:k2pw

项目源码:
链接:https://pan.baidu.com/s/1ROC3bnlO7ZXXqFidAdewOA
提取码:h30y

1、Web架构目录
在这里插入图片描述
2、配置前端页面(Thymeleaf)
注意:每个页面都配置

xmlns:th=“http://www.thymeleaf.org”

在这里插入图片描述

2、模拟数据库

1、编写实体类
在这里插入图片描述
Department

package com.jowell.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @Description: 部门表
 * @Author: JoWell
 * @Date: 2021/6/15 9:17
 * @Version: v1.0
 */

@AllArgsConstructor
@NoArgsConstructor
@Data

public class Department {
    private Integer id;
    private String departmentName;
}

Employee

package com.jowell.pojo;

import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Date;

/**
 * @Description: 员工表
 * @Author: JoWell
 * @Date: 2021/6/15 9:18
 * @Version: v1.0
 */

@NoArgsConstructor
@Data
public class Employee {
    private Integer id;
    private String lastName;
    private String email;
    private Integer sex;
    private Department department;
    private 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();
    }
}

2编写mapper层(模拟数据库的数据)

DepartmentMapper:

package com.jowell.mapper;

import com.jowell.pojo.Department;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 部门Mapper
 * @Author: JoWell
 * @Date: 2021/6/15 9:20
 * @Version: v1.0
 */
@Repository
public class DepartmentMapper {

    //模拟数据库中的数据
    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);
    }
}

EmployeeMapper:

package com.jowell.mapper;

import com.jowell.pojo.Department;
import com.jowell.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;

/**
 * @Description: 员工Mapper
 * @Author: JoWell
 * @Date: 2021/6/15 9:31
 * @Version: v1.0
 */
@Repository
public class EmployeeMapper {

    //模拟数据库中的数据
    private static Map<Integer, Employee> employees = null;

    //员工所属的部门
    @Autowired
    private DepartmentMapper departmentMapper;

    //初始话数据
    static {
        employees = new HashMap<Integer, Employee>();
        employees.put(1001, new Employee(1001, "AA", "A2280253534@qq.com", 0, new Department(101, "教学部")));
        employees.put(1002, new Employee(1002, "BB", "B2280253534@qq.com", 1, new Department(102, "市场部")));
        employees.put(1003, new Employee(1003, "CC", "C2280253534@qq.com", 0, new Department(103, "教研部")));
        employees.put(1004, new Employee(1004, "DD", "D2280253534@qq.com", 1, new Department(104, "运营部")));
        employees.put(1005, new Employee(1005, "EE", "E2280253534@qq.com", 0, new Department(105, "销售部")));
    }

    //主键自增
    private static Integer initId = 1006;

    //增加员工
    public void save(Employee employee) {
        if (employee.getId() == null) {
            employee.setId(initId++);
        }

        employee.setDepartment(departmentMapper.getDepartmentById(employee.getDepartment().getId()));

        employees.put(employee.getId(),employee);
    }

    //查询全部员工
    public Collection<Employee> getEmployeeAll(){
        return employees.values();
    }

    //通过Id查询员工
    public Employee getEmployeeById(Integer id){
        return employees.get(id);
    }
    
    //删除员工
    public void deleteEmployee(Integer id){
        employees.remove(id);
    }
}

3、登录页实现
在这里插入图片描述

在其中新建一个自己的配置类MyMvcConfig,进行视图跳转

@Configuration
public class MyMvConfig implements WebMvcConfigurer {

    //视图解析器
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/index.html").setViewName("index");
    }
}

配置完进行测试:如下页面效果
在这里插入图片描述
可以看出是没有样式的!这个时候我们就要接管Thymeleaf

修改404.html:
在这里插入图片描述
修改dashboard.html:
在这里插入图片描述
修改index.html:
在这里插入图片描述
修改list.html:
在这里插入图片描述
再次访问登录页:
在这里插入图片描述

3、页面国际化

1、统一properties编码为UTF-8
在这里插入图片描述
2、编写i18n国际化资源文件
在这里插入图片描述
在这里插入图片描述
以下方式命名,IDEA会帮我们识别这是个国际化配置包,自动绑定在一起转换成如下的模式:
在这里插入图片描述

然后打开英文或者中文语言的配置文件,点击Resource Bundle进入可视化编辑页面
在这里插入图片描述
进入到可视化编辑页面后,点击加号,添加属性,首先新建一个login.tip代表首页中的提示
在这里插入图片描述
然后对该提示分别做三种情况的语言配置,在三个对应的输入框输入即可(注意:IDEA2020.1可能无法保存,建议直接在配置文件中编写)
在这里插入图片描述
然后打开三个配置文件的查看其中的文本内容,可以看到已经做好了全部的配置
login.properties:

login.tip=请登录
login.password=密码
login.remember=记住我
login.btn=登录
login.username=用户名

login_en_US.properties:

login.tip=Please sign in
login.password=password
login.remember=remember me
login.btn=login
login.username=username

login_zh_CN.properties:

login.tip=请登录
login.password=密码
login.remember=记住我
login.btn=登录
login.username=用户名

配置yml 配置类中配置
在这里插入图片描述

4、配置国际化资源文件名称

1、首页获取显示国际化值:
在这里插入图片描述
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="@{/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>
    <input type="text" class="form-control" name="username" th:placeholder="#{login.username}" required="" autofocus="">
    <input type="password" class="form-control" name="password" 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>

重启项目,访问首页,可以发现已经自动识别为中文:
在这里插入图片描述

5. 配置国际化组件实现中英文切换

1. 添加中英文切换标签链接

<a class="btn btn-sm">中文</a>
<a class="btn btn-sm">English</a>

在这里插入图片描述
然后这两个标签上加上跳转链接并带上相应的参数:

<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. 自定义地区解析器组件:

怎么实现我们自定义的地区解析器呢?我们首先来分析一波源码

在Spring中有关于国际化的两个类:

Locale:代表地区,每一个Locale对象都代表了一个特定的地理、政治和文化地区 LocaleResolver:地区解析器

我们在config包下新建MyLocaleResolver,作为自己的国际化地区解析器
在这里插入图片描述
我们在index.html中,编写了对应的请求跳转

如果点击中文按钮,则跳转到/index.html(l=‘zh_CN’)页面
如果点击English按钮,则跳转到/index.html(l=‘en_US’)页面

MyLocaleResolver代码:

package com.jowell.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;

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();
}

我们重启项目,来访问一下,发现点击按钮可以实现成功切换!
点击中文按钮,跳转到http://localhost:8080/index.html?l=zh_CN,显示为中文

在这里插入图片描述
点击English按钮,跳转到http://localhost:8080/index.html?l=en_US,显示为英文
在这里插入图片描述

6. 登录功能实现

1、首先在index.html中的表单编写一个提交地址/login,并给名称和密码输入框添加username和password属性为了后面的传参
在这里插入图片描述
2、然后编写对应的controller
在这里插入图片描述
定义登录控制器:代码如下

package com.jowell.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.util.StringUtils;

@Controller
public class LoginController {

    @RequestMapping("/login")
    public String Login(@RequestParam("username") String username, @RequestParam("password") String password, Model model) {
        //如果用户名和密码正确
        if (username.equals("admin") && password.equals("123456")) {
            //跳转到dashboard页面
            return "dashboard";
        } else { //如果用户名或者密码不正确
            //显示错误信息
            model.addAttribute("msg","用户名或密码错误");
            //跳转到首页
            return "index";
        }
    }

}

然后我们在index.html首页中加一个标签用来显示controller返回的错误信息:

<!--如果用户为空,则不显示-->
    <p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>

3、我们再测试一下,启动主程序,访问localhost:8080如果我们输入正确的用户名和密码
页面展示:
在这里插入图片描述
则重新跳转到dashboard页面,浏览器url为http://localhost:8080/user/login?username=admin&password=123456
在这里插入图片描述
测试2:
随便输入错误的用户名12,输入错误的密码12

浏览器url为http://localhost:8080/user/login?username=12&password=123456,页面上附有错误提示信息
页面展示:
在这里插入图片描述
到此我们的登录功能实现完毕,但是有一个很大的问题,浏览器的url暴露了用户的用户名和密码,这在实际开发中可是重大的漏洞,泄露了用户信息,因此我们需要编写一个映射

我们在自定义的配置类MyMvcConfig中加一句代码

registry.addViewController("/main.html").setViewName("dashboard");

也就是访问/main.html页面就跳转到dashboard页面

然后我们稍稍修改一下LoginController,当登录成功时重定向到main.html页面,也就跳转到了dashboard页面

package com.jowell.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.util.StringUtils;

@Controller
public class LoginController {

    @RequestMapping("/login")
    public String Login(@RequestParam("username") String username, @RequestParam("password") String password, Model model) {
        //如果用户名和密码正确
        if (username.equals("admin") && password.equals("123456")) {
            //跳转到dashboard页面
            return "redirect:/main.html"; //重定向到main.html页面,也就是跳转到dashboard页面
        } else { //如果用户名或者密码不正确
            //显示错误信息
            model.addAttribute("msg","用户名或密码错误");
            //跳转到首页
            return "index";
        }
    }

}

再次访问:在这里插入图片描述但是这又出现了新的问题,无论登不登陆,我们访问localhost/main.html都会跳转到dashboard的页面,这就引入了接下来的拦截器

7、 登录拦截器配置

用户登录成功后,后台会得到用户信息;如果没有登录,则不会有任何的用户信息;

我们就可以利用这一点通过拦截器进行拦截:

当用户登录时将用户信息存入session中,访问页面时首先判断session中有没有用户的信息
如果没有,拦截器进行拦截;
如果有,拦截器放行

因此我们首先在LoginController中当用户登录成功后,存入用户信息到session中
代码如下:

package com.jowell.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpSession;

/**
 * @Description: 登录控制器
 * @Author: JoWell
 * @Date: 2021/6/15 14:34
 * @Version: v1.0
 */
@Controller
public class LoginController {

    @RequestMapping("/login")
    public String Login(@RequestParam("username") String username, @RequestParam("password") String password, Model model, HttpSession session) {
        //如果用户名和密码正确
        if (username.equals("admin") && password.equals("123456")) {
            session.setAttribute("LoginUser",username);
            //跳转到dashboard页面
            return "redirect:/main.html"; //重定向到main.html页面,也就是跳转到dashboard页面
        } else { //如果用户名或者密码不正确
            //显示错误信息
            model.addAttribute("msg","用户名或密码错误");
            //跳转到首页
            return "index";
        }
    }

}

然后再在实现自定义的登录拦截器,继承HandlerInterceptor接口
代码如下:

package com.jowell.config;

import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description: 拦截器
 * @Author: JoWell
 * @Date: 2021/6/15 16:06
 * @Version: v1.0
 */
public class LoginHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //用户登录成功后,应该有自己的session
        Object user = request.getSession().getAttribute("LoginUser");

        if (user == null) {
            request.setAttribute("msg", "您没有权限,请先登录");
            request.getRequestDispatcher("/index.html").forward(request, response);
            return false;
        } else {
            return true;
        }
    }
}

然后配置到bean中注册,在MyMvcConfig配置类中,重写关于拦截器的方法,添加我们自定义的拦截器,注意屏蔽静态资源及主页以及相关请求的拦截

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginHandlerInterceptor())
                .addPathPatterns("/**") //拦截所有请求
                .excludePathPatterns("/index.html", "/", "/login", "/css/**", "/js/**", "/img/**"); //排除拦截的内容
    }

然后重启主程序进行测试,直接访问http://localhost:8080/main.html
在这里插入图片描述
提示权限不够,请先登录,我们登录一下:
进入到dashboard页面:
在这里插入图片描述

8、 展示员工信息

1、实现Customers视图跳转
点击dashboard.html页面中的Customers展示跳转到list.html页面显示所有员工信息
在这里插入图片描述
因此,我们首先给dashboard.html页面中Customers部分标签添加href属性,实现点击该标签请求/emps路径跳转到list.html展示所有的员工信息
在这里插入图片描述同样修改list.html对应该的代码为上述代码:
list.html页面:
在这里插入图片描述

在实际开发中:我们在templates目录下新建一个包emp,用来放所有关于员工信息的页面,我们将list.html页面移入该包中
在这里插入图片描述
2、然后编写请求对应的controller,处理/emps请求,在controller包下,新建一个EmployeeController类
在这里插入图片描述
EmployeeController代码:

package com.jowell.controller;

import com.jowell.mapper.EmployeeMapper;
import com.jowell.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;

/**
 * @Description: 员工控制器
 * @Author: JoWell
 * @Date: 2021/6/15 16:45
 * @Version: v1.0
 */
@Controller
public class EmployeeController {

    @Autowired
    private EmployeeMapper employeeMapper;

    @RequestMapping("/emps")
    public String EmployeeList(Model model){
        Collection<Employee> employeeAll = employeeMapper.getEmployeeAll();
        model.addAttribute("emps", employeeAll);
        return "emp/list";
    }

}

3、然后我们重启主程序进行测试,登录到dashboard页面,再点击Customers,成功跳转到/emps
在这里插入图片描述
但是有问题:
1.我们点击了Customers后,它应该处于高亮状态,但是这里点击后还是普通的样子,高亮还是在Dashboard上
2.list.html和dashboard.html页面的侧边栏和顶部栏是相同的,可以抽取出来

4、提取页面公共部分
在这里插入图片描述

利用th:fragment标签抽取公共部分(顶部导航栏和侧边栏)

common.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" 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>
</body>
</html>

然后删除dashboard.html和list.html中顶部导航栏和侧边栏的代码
在这里插入图片描述
再次重启主程序测试一下,登陆成功后,可以看到已经没有了顶部导航栏和侧边栏
在这里插入图片描述
:这是因为我们删除了公共部分,还没有引入,我们分别在dashboard.html和list.html删除的部分插入提取出来的公共部分topbar和sidebar

<!--顶部导航栏-->
<div th:replace="~{commons/commons::topbar}" }></div>
<!--侧边栏-->
<div th:replace="~{commons/commons::siderbar}"></div>

在这里插入图片描述
然后在次重启测试:
在这里插入图片描述
5、点击高亮处理

在页面中,使高亮的代码是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,利用三元运算符判断决定是否高亮在这里插入图片描述
设置完成再次重启:
在这里插入图片描述
6、 显示员工信息
在list.html页面修改,显示我们自己的数据值
在这里插入图片描述
修改完成后,重启主程序,登录完成后查看所有员工信息,如图下所示:
在这里插入图片描述
7、接下来修改一下性别的显示和date的显示,并添加编辑和删除两个标签,为后续做准备
在这里插入图片描述
编写完成,启动测试,展示图如下:
在这里插入图片描述

9、 添加员工信息

1.在templates/emp下新建一个add.html:在这里插入图片描述
2.add.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/common::topbar}"></div>

		<div class="container-fluid">
			<div class="row">

				<!--侧边栏-->
				<div th:replace="~{commons/common::sidebar(active='list.html')}"></div>

				<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
					<form action="/emp" method="post">
						<div class="form-group">
							<label>LastName</label>
							<input type="text" name="lastName" class="form-control" placeholder="lastname:zsr">
						</div>
						<div class="form-group">
							<label>Email</label>
							<input type="email" name="email" class="form-control" placeholder="email:xxxxx@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">
								<!--注意这里的name是department.id,因为传入的参数为id-->
								<option th:each="dept:${departments}" th:text="${dept.getDepartmentName()}" th:value="${dept.getId()}">请选择部门</option>
							</select>
						</div>
						<div class="form-group">
							<label>Birth</label>
							<!--springboot默认的日期格式为yy/MM/dd-->
							<input type="text" name="date" class="form-control" placeholder="birth:yyyy-MM-dd">
						</div>
						<button type="submit" class="btn btn-primary">添加</button>
					</form>
				</main>
			</div>
		</div>

		<!-- Bootstrap core JavaScript
    ================================================== -->
		<!-- Placed at the end of the document so the pages load faster -->
		<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>

3.重启测试,成功显示所有部门
在这里插入图片描述
4.页面添加员工请求
在add.html页面,当我们填写完信息,点击添加按钮,应该完成添加返回到list页面,展示新的员工信息;因此在add.html点击添加按钮的一瞬间,我们同样发起一个请求/add,与上述提交按钮发出的请求路径一样,但这里发出的是post请求
在这里插入图片描述
然后编写对应的controller,同样在EmployeeController中添加一个方法addEmp用来处理点击添加按钮的操作:

    @PostMapping("/emp")
    public String addEmp(Employee employee){
        //保存员工信息
        employeeMapper.save(employee);
        return "redirect:/emps";
    }

我们重启主程序,进行测试,进入添加页面,填写相关信息,注意日期格式默认为yyyy-MM-dd
在这里插入图片描述
然后点击添加按钮,成功实现添加员工
在这里插入图片描述

10、修改员工信息

1. list页面编辑按钮增添请求
在这里插入图片描述
然后编写对应的controller,在EmployeeController中添加一个方法edit用来处理list页面点击编辑按钮的操作,返回到edit.html编辑员工页面,我们即将创建

    //跳转员工修改页面
    //restful风格接收参数
    @GetMapping("/emp/{id}")
    public String toUpdateEmp(@PathVariable("id") Integer id,Model model){
        //查询指定id的员工,添加到empByID中,用于前端接收
        Employee employeeById = employeeMapper.getEmployeeById(id);
        //查出所有的部门信息,添加到departments中,用于前端接收
        model.addAttribute("emp",employeeById);
        //查出部门信息
        Collection<Department> departments = departmentMapper.getDepartments();
        model.addAttribute("departments",departments);
        return "emp/updateEmp";//返回到编辑员工页面
    }

2. 创建编辑员工页面updateEmp:
在这里插入图片描述
updateEmp.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/common::topbar}"></div>

		<div class="container-fluid">
			<div class="row">

				<!--侧边栏-->
				<div th:replace="~{commons/common::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="@{/emp}" method="post">
						<input type="hidden" name="id" th:value="${emp.getId()}">
						<div class="form-group">
							<label>LastName</label>
							<input th:value="${emp.getLastName()}" type="text" name="lastName" class="form-control"
								   placeholder="lastname:zsr">
						</div>
						<div class="form-group">
							<label>Email</label>
							<input th:value="${emp.getEmail()}" type="email" name="email" class="form-control"
								   placeholder="email:xxxxx@qq.com">
						</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"></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"></label>
							</div>
						</div>
						<div class="form-group">
							<label>department</label>
							<!--注意这里的name是department.id,因为传入的参数为id-->
							<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>
							<!--springboot默认的日期格式为yy/MM/dd-->
							<input th:value="${#dates.format(emp.getBirth(),'yyyy-MM-dd HH:mm')}" type="text" name="birth" class="form-control"
								   placeholder="birth:yy/MM/dd">
						</div>
						<button type="submit" class="btn btn-primary">修改</button>
					</form>
				</main>

			</div>
		</div>

		<!-- Bootstrap core JavaScript
    ================================================== -->
		<!-- Placed at the end of the document so the pages load faster -->
		<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>

重启测试,同样修改1001号用户名称为abcd:
在这里插入图片描述
成功修改并返回到list.html

11、删除员工信息

当我们点击删除标签时,应该发起一个请求,删除指定的用户,然后重新返回到list页面显示员工数据
在这里插入图片描述

然后编写对应的controller,处理点击删除按钮的请求,删除指定员工,重定向到/emps请求,更新员工信息

    //删除员工操作
    @GetMapping("/delete/{id}")
    public String deleteEmp(@PathVariable("id") Integer id){
        employeeMapper.deleteEmployee(id);
        return "redirect:/emps";
    }

重启测试,点击删除按钮即可删除指定员工

12、注销登录操作

在我们提取出来的公共commons页面,顶部导航栏处中的标签添加href属性,实现点击发起请求/user/logout在这里插入图片描述
然后编写对应的controller,处理点击注销标签的请求,在LoginController中编写对应的方法,清除session,并重定向到首页

    //注销
    @RequestMapping("/user/loginout")
    public String  loginOut(HttpSession session){
        session.invalidate();
        return "redirect:/index";
    }

重启测试,登录成功后,点击log out即可退出到首页!

springbootWeb核心功能就是这些,很简单
在这里插入图片描述

评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

喝汽水的猫^

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值