SpringBoot完整版(三)- 员工管理系统

SpringBoot完整版(三)- 员工管理系统

一、准备工作

1.1 新建Spring Boot项目并导入资源

(1)新建spring boot项目
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
删除文件
在这里插入图片描述
(2)导入静态资源

静态资源下载

导入静态资源
在这里插入图片描述

1.2 创建基本信息类(pojo)

注意: 本项目暂时是采用模拟数据库的方法来获取数据,未用到数据库的相关操作。
(1)引入lombok依赖,注意还需要安装lombok插件。(之前已经引入)

<!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

(2)创建部门实体类Department.java

package com.example.employee_management.pojo;

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

/**
 * @className: Department
 * @description: 部分信息类
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Department {

    /**
     * 部门id
     */
    private Integer id;
    /**
     * 部门名
     */
    private String departmentName;
}

(3)创建员工实体类Employee.java

1.3 创建DAO层

(1)部门dao
DepartmentDao.java

package com.example.employee_management.dao;

import com.example.employee_management.pojo.Department;
import org.springframework.stereotype.Repository;

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

/**
 * @className: DepartmentDao
 * @description: 部门dao
 */
@Repository
public class DepartmentDao {

    /**
     * 模拟数据库信息
     */
    private static Map<Integer, Department> departmentMap = null;

    static {
        //创建一个部门表
        departmentMap = new HashMap<>();

        departmentMap.put(101, new Department(101, "教学部"));
        departmentMap.put(102, new Department(102, "市场部"));
        departmentMap.put(103, new Department(103, "教研部"));
        departmentMap.put(104, new Department(104, "运营部"));
        departmentMap.put(105, new Department(105, "后勤部"));

    }

    /**
     * 获得所有部门信息
     *
     * @return
     */
    public Collection<Department> getAllDepartments() {
        return departmentMap.values();
    }

    /**
     * 通过id得到部门
     *
     * @param id
     * @return
     */
    public Department getDepartmentById(Integer id) {
        return departmentMap.get(id);
    }

}

(2)员工dao
EmployeeDao.java

package com.example.employee_management.dao;

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

/**
 * @className: EmployeeDao
 * @description: 员工dao
 */
@Repository
public class EmployeeDao {

    /**
     * 模拟数据库信息
     */
    private static Map<Integer, Employee> employeeMap = null;

    /**
     * 员工所属部门
     */
    @Autowired
    private DepartmentDao departmentDao;

    static {
        //创建一个员工表
        employeeMap = new HashMap<>();

        employeeMap.put(1001, new Employee(1001, "a", "123@123.com", 1, new Department(101, "教学部")));
        employeeMap.put(1002, new Employee(1002, "b", "234@123.com", 0, new Department(102, "市场部")));
        employeeMap.put(1003, new Employee(1003, "c", "345@123.com", 1, new Department(103, "教研部")));
        employeeMap.put(1004, new Employee(1004, "d", "456@123.com", 0, new Department(104, "运营部")));
        employeeMap.put(1005, new Employee(1005, "e", "567@123.com", 1, new Department(105, "后勤部")));

    }

    /**
     * 员工id,相当于数据库中的主键
     */
    private static Integer initId = 1006;

    /**
     * 保存新增员工
     *
     * @param employee
     */
    public void save(Employee employee) {
        //id自增
        if (employee.getId() == null) {
            employee.setId(initId++);
        }

        //设置部门
        employee.setDepartment(departmentDao.getDepartmentById(employee.getDepartment().getId()));

        //放入容器中去
        employeeMap.put(employee.getId(), employee);

    }

    /**
     * 得到所有员工信息
     *
     * @return
     */
    public Collection<Employee> getAllEmployees() {
        return employeeMap.values();
    }

    /**
     * 通过id得到员工信息
     *
     * @param id
     * @return
     */
    public Employee getEmployeeById(Integer id) {
        return employeeMap.get(id);
    }

    /**
     * 通过id删除员工信息
     *
     * @param id
     */
    public void deleteEmployeeById(Integer id) {
        employeeMap.remove(id);
    }

}

二、首页实现

2.1 在(config)包下创建MVC配置类来打开首页

(1)创建mvc配置类
MyMvcConfig.java

package com.example.employee_management.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @className: MyMvcConfig
 * @description: MVC 控制器  借助注解完成控制器而不用手动编写
 */
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {

    /**
     * MVC 添加首页控制器
     *
     * @param registry
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        //这里 “/”和“/index.html”效果一样,因为web项目默认页是index.html
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/index.html").setViewName("index");
    }
}

(2)启动项目

失败: 在启动类头部声明@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})就可以了。

成功: 在浏览器中输入http://localhost:8080/index.html
在这里插入图片描述
说明MVC配置成功,但是css样式却未加载成功。

2.2 修改index.html文件

(1)修改首页index.html文件
主要是引入themeleaf命名空间xmlns:th="http://www.thymeleaf.org"以及在引入静态资源的地方改为themeleaf的方式。
在这里插入图片描述
为了后续开发,这里把其他几个静态页面也一并改了。

404.html
在这里插入图片描述
dashbora.html
在这里插入图片描述
list.html
在这里插入图片描述
(2)关闭模板引擎缓存(非必要)
关闭模板引擎缓存有利于进行调试,避免出现已修改代码而界面不改变的情况。
application.properties

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

在这里插入图片描述
(3)再次启动项目成功后,在浏览器中输入

http://localhost:8080/index.html

在这里插入图片描述
总结:

  • 通过MVC配置类实现控制器(结合注解)简化开发
  • 引入thymeleaf依赖
  • 修改前端页面,改为thymeleaf的形式-链接(@{}

三、国际化

通俗地讲,国际化就是实现网页语言的切换

3.1 配置首页的国际化

(1)国际化涉及语言,就得要考虑编码,故应使IDEA编码格式为utf-8
在这里插入图片描述
(2)在resources目录下创建i18n(internationalization)目录,并在此目录下创建下列文件
在这里插入图片描述
注意“Resource Bundle ‘login’”目录是系统自动生成的。
(3)配置登录元素国际化
点击“Resource Bundle”按钮进入可视化界面
在这里插入图片描述
点击加号新建一个property key:login.tip
在这里插入图片描述
在这里插入图片描述
相应的再新建其他几个property key
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
(4)在application.properties文件中新增国际化的相关配置

#配置国际化相关文件位置
spring.messages.basename=i18n.login

3.2 修改前端页面

修改index.html文件,主要是引入国际化。
在这里插入图片描述
启动项目成功后,在浏览器中输入http://localhost:8080/index.html可得到如下页面:
在这里插入图片描述

3.3 新建国际化解析器配置类

在Spring中有一个国际化的Locale (区域信息对象);里面有一个叫做LocaleResolver (获取区域信息对象)的解析器!

我们去我们webmvc自动配置文件,寻找一下!看到SpringBoot默认配置:

@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = "spring.mvc", name = "locale")
public LocaleResolver localeResolver() {
    // 容器中没有就自己配,有的话就用用户配置的
    if (this.mvcProperties.getLocaleResolver() == WebMvcProperties.LocaleResolver.FIXED) {
        return new FixedLocaleResolver(this.mvcProperties.getLocale());
    }
    // 接收头国际化分解
    AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
    localeResolver.setDefaultLocale(this.mvcProperties.getLocale());
    return localeResolver;
}

AcceptHeaderLocaleResolver 这个类中有一个方法

public Locale resolveLocale(HttpServletRequest request) {
    Locale defaultLocale = this.getDefaultLocale();
    // 默认的就是根据请求头带来的区域信息获取Locale进行国际化
    if (defaultLocale != null && request.getHeader("Accept-Language") == null) {
        return defaultLocale;
    } else {
        Locale requestLocale = request.getLocale();
        List<Locale> supportedLocales = this.getSupportedLocales();
        if (!supportedLocales.isEmpty() && !supportedLocales.contains(requestLocale)) {
            Locale supportedLocale = this.findSupportedLocale(request, supportedLocales);
            if (supportedLocale != null) {
                return supportedLocale;
            } else {
                return defaultLocale != null ? defaultLocale : requestLocale;
            }
        } else {
            return requestLocale;
        }
    }
}

那假如我们现在想点击链接让我们的国际化资源生效,就需要让我们自己的Locale生效!

我们去自己写一个自己的LocaleResolver,可以在链接上携带区域信息!

修改 index.html
在这里插入图片描述

<!-- 这里传入参数不需要使用 ?使用 (key=value)-->
<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>

(1)新建国际化解析器配置类
MyLocaleResolver.java

package com.example.employee_management.config;

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;

/**
 * @className: MyLocalResolver
 * @description: 国际化解析器配置类
 */
public class MyLocaleResolver implements LocaleResolver {
    /**
     * 解析请求
     *
     * @param httpServletRequest
     * @return
     */
    @Override
    public Locale resolveLocale(HttpServletRequest httpServletRequest) {

        //获取请求中的语言参数
        String language = httpServletRequest.getParameter("language");

        //如果没有就使用默认的
        Locale locale = Locale.getDefault();

        //请求链接携带了国际化参数
        if (!StringUtils.isEmpty(language)) {

            //格式:zh_CN
            String[] splits = language.split("_");
            //国家 地区
            locale = new Locale(splits[0], splits[1]);

        }

        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {

    }
}

(2)在MVC配置类里面将定义的国际化组件放入ioc容器中

package com.example.employee_management.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @className: MyMvcConfig
 * @description: MVC 控制器  借助注解完成控制器而不用手动编写
 */
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {

    /**
     * MVC 添加首页控制器
     *
     * @param registry
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        //这里 “/”和“/index.html”效果一样,因为web项目默认页是index.html
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/index.html").setViewName("index");
    }

    /**
     * 将国际化组件放入ioc容器中
     *
     * @return
     */
    @Bean
    public LocaleResolver localeResolver() {
        return new MyLocaleResolver();
    }

}

(3)再次启动项目成功后,在浏览器中输入http://localhost:8080/index.html现在点击“中文”“English”链接即可实现语言的切换。
在这里插入图片描述
总结: 关于实现国际化需要注意的地方有:

  • 对于前端界面的每一个元素都需要创建国际化配置项,并且要在springboot默认的配置文件里指明国际化配置项文件位置
  • 需要创建一个国际化配置类,并且要在之前建立好的MVC配置类里面将国际化组件放入ioc容器中

四、登录功能实现

4.1 新建登录控制器

LoginController.java

package com.example.employee_management.controller;

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

/**
 * @className: LoginController
 * @description: 登录控制器
 */
@Controller
public class LoginController {

    /**
     * 登录
     *
     * @param username
     * @param password
     * @param model
     * @return
     */
    @RequestMapping("/user/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password, Model model) {

        //用户名不为空且密码正确  注意这里的数据是默认密码为123456,便于调试
        if (!StringUtils.isEmpty(username) && "123456".equals(password)) {
            return "redirect:/main.html";
        } else {
            //用户名或密码错误
            model.addAttribute("msg", "用户名或密码错误");
            return "index";
        }
    }
}

4.2 修改index.html文件

(1)修改表单的action为@{/user/login}
(2)添加提示信息
(3)对于用户名和密码输入框添加name属性

<!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">
<!--修改表单的action为@{/user/login}-->
<form class="form-signin" th:action="@{/user/login}">
    <img class="mb-4" th:src="@{/img/bootstrap-solid.svg}" alt="" width="72" height="72" src="">
    <!--修改-->
    <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>-->
    <label>
        <!--修改-->
        <input type="text" name="username" class="form-control" th:placeholder="#{login.username}" required="" autofocus="">
    </label>
    <!--修改-->
    <!--<label class="sr-only" th:text="#{login.password}">Password</label>-->
    <label>
        <!--修改-->
        <input type="password" name="password" class="form-control" th:placeholder="#{login.password}" required="">
    </label>
    <div class="checkbox mb-3">
        <!--修改-->
        <label>
            <input type="checkbox" value="remember-me">[[#{login.rememberMe}]]
        </label>
    </div>
    <!--修改-->
    <button class="btn btn-lg btn-primary btn-block" type="submit">[[#{login.signInBtn}]]</button>
    <p class="mt-5 mb-3 text-muted">© 2017-2018</p>
    <!--修改-->
    <a class="btn btn-sm" th:href="@{/index.html(language='zh_CN')}">中文</a>
    <a class="btn btn-sm" th:href="@{/index.html(language='en_US')}">English</a>
</form>

</body>

</html>

4.3 添加用户主页

在MyMvcConfig类中添加用户主页页面控制器

package com.example.employee_management.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @className: MyMvcConfig
 * @description: MVC 控制器  借助注解完成控制器而不用手动编写
 */
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {

    /**
     * MVC 添加首页控制器
     *
     * @param registry
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        //这里 “/”和“/index.html”效果一样,因为web项目默认页是index.html
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/index.html").setViewName("index");

        //添加用户主页
        registry.addViewController("/main.html").setViewName("dashboard");
    }

    /**
     * 将国际化组件放入ioc容器中
     *
     * @return
     */
    @Bean
    public LocaleResolver localeResolver() {
        return new MyLocaleResolver();
    }

}

启动项目。输入正确的用户名和密码后,会自动跳转到dashboard.html页面;当输入错误时会有提示信息
在这里插入图片描述
总结: 实现登录功能需要注意的地方有:

  • 建立一个登录控制器类,且要在MVC配置类中作相应配置
  • 利用form表单提交信息
  • 目前实现的登录功能不完善,后续需要加上拦截器使其更安全

五、登录拦截器

5.1 新建登录拦截器

LoginHandlerIntercepter.java

package com.example.employee_management.config;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @className: LoginHandlerIntercepter
 * @description: 登录拦截器
 */
public class LoginHandlerIntercepter implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取登录用户的session
        Object loginUser = request.getSession().getAttribute("loginUser");

        //session不存在,即用户尚未登录
        if (loginUser == null) {
            request.setAttribute("msg", "请先登录");
            //返回首页
            request.getRequestDispatcher("/index.html").forward(request, response);

            return false;

        } else {
            return true;
        }
    }
}

5.2 在MVC配置类中添加登录拦截器

MyMvcConfig.java

package com.example.employee_management.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @className: MyMvcConfig
 * @description: MVC 控制器  借助注解完成控制器而不用手动编写
 */
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {

    /**
     * MVC 添加首页控制器
     *
     * @param registry
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        //这里 “/”和“/index.html”效果一样,因为web项目默认页是index.html
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/index.html").setViewName("index");

        //添加用户主页
        registry.addViewController("/main.html").setViewName("dashboard");
    }

    /**
     * 将国际化组件放入ioc容器中
     *
     * @return
     */
    @Bean
    public LocaleResolver localeResolver() {
        return new MyLocaleResolver();
    }

    /**
     * 添加登录拦截器
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginHandlerIntercepter()).addPathPatterns("/**")
                .excludePathPatterns("/index.html", "/", "/user/login", "/css/**", "/js/**", "/img/**");
    }
}

5.3 修改登录控制器:添加session来保证拦截器正常运行

LoginController.java

package com.example.employee_management.controller;

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

import javax.servlet.http.HttpSession;

/**
 * @className: LoginController
 * @description: 登录控制器
 */
@Controller
public class LoginController {

    /**
     * 登录
     *
     * @param username
     * @param password
     * @param model
     * @return
     */
    @RequestMapping("/user/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password, Model model, HttpSession session) {

        //用户名不为空且密码正确  注意这里的数据是默认密码为123456,便于调试
        if (!StringUtils.isEmpty(username) && "123456".equals(password)) {
            session.setAttribute("loginUser", username);
            return "redirect:/main.html";
        } else {
            //用户名或密码错误
            model.addAttribute("msg", "用户名或密码错误");
            return "index";
        }
    }
}

启动项目后,在浏览器中输入localhost:8080/main.html
在这里插入图片描述
登录拦截器的功能已完成。

六、展示员工列表

修改dashboard.html
在这里插入图片描述

6.1 新建员工管理控制器

EmployeeController.java

package com.example.employee_management.controller;

import com.example.employee_management.dao.EmployeeDao;
import com.example.employee_management.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;

/**
 * @className: EmployeeController
 * @description: 员工管理控制器
 */
@Controller
public class EmployeeController {

    @Autowired
    EmployeeDao employeeDao;

    /**
     * 员工列表
     *
     * @return
     */
    @RequestMapping("/employees")
    public String list(Model model) {

        Collection<Employee> employees = employeeDao.getAllEmployees();
        model.addAttribute("employees", employees);
        return "employees/list";

    }
}

6.2 抽取前端页面相同代码

为简化开发并且提高代码的复用性,这里将顶部导航栏和侧边栏单独抽取出来放在commons目录下的common.html文件中。
在这里插入图片描述
common.html

<!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="@{/employees}">
                    <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-users">
                        <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path>
                        <circle cx="9" cy="7" r="4"></circle>
                        <path d="M23 21v-2a4 4 0 0 0-3-3.87"></path>
                        <path d="M16 3.13a4 4 0 0 1 0 7.75"></path>
                    </svg>
                    员工管理
                </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>

dashboard.html
在这里插入图片描述

	<!--顶部导航栏-->
	<div th:replace="~{commons/common::topbar}"></div>
	
	<!--侧边栏-->
	<div th:replace="~{commons/common::sidebar(active='main.html')}"></div>

list.html
在这里插入图片描述

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

6.3 启动项目

启动项目后在浏览器中输入localhost:8080/

然后输入用户名和密码后便可进入主页。
在这里插入图片描述
点击员工管理,便可进入员工列表页面
在这里插入图片描述

6.4 修改list.html使其读取数据

由于读取数据不止一个,因此需要用到th:each来进行遍历,具体应放在员工表格哪里。此外再增加“编辑”和“删除”按钮。
list.html
在这里插入图片描述

<thead>
	<tr>
		<th>id</th>
		<th>username</th>
		<th>email</th>
		<th>gender</th>
		<th>department</th>
		<th>birth</th>
		<th>操作</th>
	</tr>
</thead>
<tbody>
<tr th:each="employee:${employees}">
	<td th:text="${employee.getId()}"></td>
	<td th:text="${employee.getEmployeeName()}"></td>
	<td th:text="${employee.getEmail()}"></td>
	<td th:text="${employee.getGender()==0 ? '':''}"></td>
	<td th:text="${employee.department.getDepartmentName()}"></td>
	<td th:text="${#dates.format(employee.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>

在这里插入图片描述

七、增加员工实现

7.1 在员工展示页面(list.html)中新增“添加员工按钮”

在这里插入图片描述

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

7.2 在员工控制器(EmployeeController)里面新增“添加员工方法”

由于添加员工一是需要跳转到“添加页面”,二是提交“添加信息”并跳转到员工信息展示页面,相应的在员工控制器(EmployeeController)里面添加如下方法:

    @Autowired
    DepartmentDao departmentDao;
    
     /**
     * 添加员工
     * @return
     */
    @GetMapping("/add")
    public String add(Model model){
        //获取所有部门信息
        Collection<Department> departments=departmentDao.getAllDepartments();
        model.addAttribute("departments",departments);
        return "employees/add";
    }


    /**
     * 提交添加员工信息
     * @return
     */
    @PostMapping("/submitadd")
    public String submitAdd(Employee employee){
        //保存用户
        employeeDao.save(employee);
        return "redirect:/employees";
    }

7.3 新建“添加用户页面”add.html

在employees目录下新建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 th:action="@{/submitadd}" method="post">
                <div class="form-group">
                    <label>employeeName</label>
                    <label>
                        <input type="text" name="employeeName" class="form-control" placeholder="a">
                    </label>
                </div>

                <div class="form-group">
                    <label>email</label>
                    <label>
                        <input type="text" name="email" class="form-control" placeholder="123@123.com">
                    </label>
                </div>

                <div class="form-group">
                    <label>gender</label>
                    <div class="form-check form-check-inline">
                        <label>
                            <input class="form-check-input" type="radio" name="gender" value="1">
                        </label>
                        <label class="form-check-label"></label>
                    </div>
                    <div class="form-check form-check-inline">
                        <label>
                            <input class="form-check-input" type="radio" name="gender" value="0">
                        </label>
                        <label class="form-check-label"></label>
                    </div>
                </div>

                <div class="form-group">
                    <label>department</label>
                    <label>
                        <select class="form-control" name="department.id">
                            <option th:each="department:${departments}"
                                    th:text="${department.getDepartmentName()}"
                                    th:value="${department.getId()}"></option>

                        </select>
                    </label>
                </div>

                <div class="form-group">
                    <label>birth</label>
                    <label>
                        <input type="text" name="birth" class="form-control" placeholder="1990-01-01">
                    </label>
                </div>

                <div>
                    <button type="submit" class="btn btn-primary">添加</button>
                </div>
            </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>

7.4 修改默认时间格式并启动项目

按照习惯,书写时间的一般格式为yyyy-MM-dd,在application.properties文件里添加如下语句

#默认日期格式
spring.mvc.date-format=yyyy-MM-dd

便可将日期改为一般格式。
启动项目后,进入员工管理页面,点击新增员工按钮,进入新增页面。
在这里插入图片描述
在这里插入图片描述
输入相应的信息,并点击添加按钮。
在这里插入图片描述
添加成功。
在这里插入图片描述
总结: 增加员工实现需要注意的地方有:

  • 需要新建一个添加员工页面。
  • 由于未使用数据库,因此新增的信息不具有持久性,再次启动项目,新增信息便会消失。
  • 理论上新增员工不能和之前的员工重复,而这里并未作判断。

八、修改员工信息

修改编辑按钮(list.html):

<a class="btn btn-sm btn-primary" th:href="@{/update/}+${employee.getId()}">编辑</a>

8.1 在员工控制器(EmployeeController)里面新增“修改员工方法”

由于修改员工一是需要跳转到“修改页面”,二是提交“修改信息”并跳转到员工信息展示页面,相应的在员工控制器(EmployeeController)里面添加如下方法:

    /**
     * 修改员工信息
     *
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/update/{id}")
    public String update(@PathVariable("id") Integer id, Model model) {

        //查找要修改员工的信息
        Employee employee = employeeDao.getEmployeeById(id);
        model.addAttribute("employee", employee);

        //获取所有部门信息
        Collection<Department> departments = departmentDao.getAllDepartments();
        model.addAttribute("departments", departments);

        return "employees/update";
    }


    /**
     * 提交修改员工信息
     *
     * @param employee
     * @return
     */
    @PostMapping("/submitupdate")
    public String submitUpdate(Employee employee) {
        employeeDao.save(employee);
        return "redirect:/employees";

    }

8.2 新建修改员工信息页面(update.html)

在employees目录下新建update.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="@{/submitupdate}" method="post">

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

                <div class="form-group">
                    <label>employeeName</label>
                    <label>
                        <input type="text" th:value="${employee.getEmployeeName()}" name="employeeName"
                               class="form-control" placeholder="a">
                    </label>
                </div>

                <div class="form-group">
                    <label>email</label>
                    <label>
                        <input type="text" th:value="${employee.getEmail()}" name="email" class="form-control"
                               placeholder="123@123.com">
                    </label>
                </div>

                <div class="form-group">
                    <label>gender</label>
                    <div class="form-check form-check-inline">
                        <label>
                            <input class="form-check-input" type="radio" name="gender" value="1"
                                   th:checked="${employee.getGender()==1}">
                        </label>
                        <label class="form-check-label"></label>
                    </div>
                    <div class="form-check form-check-inline">
                        <label>
                            <input class="form-check-input" type="radio" name="gender" value="0"
                                   th:checked="${employee.getGender()==0}">
                        </label>
                        <label class="form-check-label"></label>
                    </div>
                </div>


                <div class="form-group">
                    <label>department</label>
                    <label>
                        <select class="form-control" name="department.id">
                            <option th:each="department:${departments}"
                                    th:text="${department.getDepartmentName()}"
                                    th:value="${department.getId()}"
                                    th:selected="${department.getId()==employee.getDepartment().getId()}"></option>

                        </select>
                    </label>
                </div>


                <div class="form-group">
                    <label>birth</label>
                    <label>
                        <input type="text" th:value="${#dates.format(employee.getBirth(),'yyyy-MM-dd HH:mm:ss')}"
                               name="birth" class="form-control" placeholder="1990-01-01">
                    </label>
                </div>

                <div>
                    <button type="submit" class="btn btn-primary">修改</button>
                </div>
            </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>

8.3 启动项目

启动项目后,进入员工管理页面,点击要修改员工的“编辑”按钮。
在这里插入图片描述
输入相应的修改信息后点击提交。
在这里插入图片描述
修改成功。
在这里插入图片描述

九、删除及注销功能实现

9.1 修改员工展示页面(list.html)

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

在这里插入图片描述

9.2 在员工控制器(EmployeeController)里面新增“删除员工方法”

    /**
     * 删除员工
     * @param id
     * @return
     */
    @GetMapping("/delete/{id}")
    public String delete(@PathVariable("id")Integer id) {
        //删除员工
        employeeDao.deleteEmployeeById(id);
        return "redirect:/employees";
    }

9.3 启动项目,验证删除功能

启动项目后,打开员工展示页面,点击所要删除员工的删除链接,即可进行删除操作。
在这里插入图片描述
删除成功。
在这里插入图片描述

9.4 报错404页面

只需要在 templates 目录下新建一个error文件夹,然后把404页面放进去即可。
在这里插入图片描述
访问不正确的地址,系统自动挑战404页面
在这里插入图片描述

9.5 修改common.html文件并在登录控制器中编写相应的注销方法

由于要实现注销功能,因此要将前端页面相应的注销新增其在登录控制器中对应的链接。
common.html

<a class="nav-link" th:href="@{/user/logout}">注销</a>

在这里插入图片描述
LoginController.java

	/**
     * 注销
     * @param session
     * @return
     */
    @RequestMapping("/user/logout")
    public String logout(HttpSession session){
        //使session失效
        session.invalidate();

        return "redirect:/index.html";

    }

启动项目,登录成功后,点击“注销”
在这里插入图片描述
注销成功后会跳转到首页
在这里插入图片描述

  • 3
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值