12-员工管理系统

员工管理系统

准备工作

pojo

Department

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Department {
    private Integer id;
    private String departmentName;
}

Employee

import java.util.Date;
@Data
@NoArgsConstructor
public class Employee {
    private Integer id;
    private String lastName;
    private String email;
    private Integer gender;//0 女 1 男
    private Department department;
    private Date birth;

    public Employee(Integer id, String lastName, String email, Integer gender, Department department) {
        this.id = id;
        this.lastName = lastName;
        this.email = email;
        this.gender = gender;
        this.department = department;
        this.birth = new Date();
    }
}

dao

DepartmentDao

package com.tian.dao;

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

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
@Repository
public class DepartmentDao {
    //模拟数据库中的数据
    private static Map<Integer, Department> departments=null;
    static {
        departments=new HashMap<Integer, Department>();
        departments.put(101,new Department(101,"教学部"));
        departments.put(102,new Department(102,"市场部"));
        departments.put(103,new Department(103,"教研部"));
        departments.put(104,new Department(104,"运营部"));
        departments.put(105,new Department(105,"后勤部"));
    }
//获得所有的部门信息
    public Collection<Department> getDepartments(){
        return  departments.values();
    }
    //根据id得到部门
    public Department getDepartmentById(Integer id){
        return departments.get(id);
    }

}

EmployeeDao

package com.tian.dao;

import com.tian.pojo.Department;
import com.tian.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;
@Repository
public class EmployeeDao {
    //模拟数据库中的数据
    private static Map<Integer, Employee> employees=null;
    @Autowired
    private DepartmentDao departmentDao;
    static {
        employees=new HashMap<Integer, Employee>();
        employees.put(1001,new Employee(1001,"AA","A2545644@qq.com",0,new Department(101,"教学部")));
        employees.put(1002,new Employee(1002,"BB","B2545644@qq.com",1,new Department(101,"市场部")));
        employees.put(1003,new Employee(1003,"CC","C2545644@qq.com",0,new Department(101,"教研部")));
        employees.put(1004,new Employee(1004,"DD","D2545644@qq.com",1,new Department(101,"运营部")));
        employees.put(1005,new Employee(1005,"EE","E2545644@qq.com",0,new Department(101,"后勤部")));
    }

    //主键自增
    private static Integer initId=1006;
    //增加一个员工
    public void save(Employee employee){
        if(employee.getId()==null){
            employee.setId(initId++);
        }
        employee.setDepartment(departmentDao.getDepartmentById(employee.getDepartment().getId()));
        employees.put(employee.getId(),employee);
    }
//查询全部员工
    public Collection<Employee> getAll(){
return employees.values();
    }
//通过id查询员工
    public Employee getEmployeeById(Integer id){
        return employees.get(id);
    }
    //删除一个员工
    public void delete(Integer id){
        employees.remove(id);
    }
}

首页实现

  • com.tian.config;

MyMvcConfig

package com.tian.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/index.html").setViewName("index");
    }
}

index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body class="text-center">
<form class="form-signin" action="dashboard.html">
    <img class="mb-4" th:src="@{/img/bootstrap.png}" alt="" width="72" height="72">
    <h1 class="h3 mb-3 font-weight-normal">Please sign in</h1>
    <label class="sr-only">Username</label>
    <input type="text" class="form-control" placeholder="Username" required="" autofocus="">
    <label class="sr-only">Password</label>
    <input type="password" class="form-control" placeholder="Password" required="">
    <div class="checkbox mb-3">
    <label>
        <input type="checkbox" value="remember-me">Remember me </label>
</div>
    <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
    <p class="mt-5 mb-3 text-muted">@ 2017-2018</p>
    <a class="btn btn-sm">中文</a>
    <a class="btn btn-sm">English</a>
</form>
</body>

</html>

页面国际化

确保都是UTF-8

在这里插入图片描述

1.我们需要配置i18n文件

在这里插入图片描述

2.我们如果需要在项目中进行按钮自动切换,我们需要自定义一个组件LocaleResolver

  • MyLocaleResolver
package com.tian.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;

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;
        //放到bean
    }

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

    }
}

3.记得将自己写的组件配置到spring容器@Bean

在这里插入图片描述

4.取值 #{}

  • ()传参

在这里插入图片描述

登录功能实现

index.html

  • th:action="@{/user/login}"
<form class="form-signin" th:action="@{/user/login}">
    <img class="mb-4" th:src="@{/img/bootstrap.png}" alt="" width="72" height="72">
    <h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1>
<!--如果msg的值为空,则不显示消息-->
    <p style="color: #ff0000" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>

contoller

@Controller
public class LoginController {

    @RequestMapping("user/login")

    public String login(@RequestParam("username") String username, @RequestParam("password")  String password, Model model){
       if(!StringUtils.isEmpty(username)&&"123456".equals(password)){
            return "redirect:/main.html";
       }
        else {
            model.addAttribute("msg","用户名或密码错误");
            return "index";
       }
    }
}

config

@Configuration
public class MyMvcConfig implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/index.html").setViewName("index");
        //加一个地址 
        registry.addViewController("/main.html").setViewName("dashboard");

    }
//自定义的国际化就生效了
    @Bean
    public LocaleResolver localeResolver(){
        return new MyLocaleResolver();
    }
}

但是还是可以直接通过导航栏直接访问

登录拦截器

登陆的controller先保存信息

 if(!StringUtils.isEmpty(username)&&"1".equals(password)){
            session.setAttribute("loginUser",username);
            return "redirect:/main.html";
       }
  else {
            model.addAttribute("msg","用户名或密码错误");
            return "index";
       }

拦截器

package com.tian.config;

import org.springframework.web.servlet.HandlerInterceptor;

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

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("/").forward(request,response);
            return false;
        }else {
            return true;
        }


    }
}

MyMvcConfig

  • 拦截器添加到MyMvcConfig 来生效
  • 记得静态资源也要搞
 @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginHandlerInterceptor())
                .addPathPatterns("/*")
                .excludePathPatterns("index.html","/","/index","/user/login","/img/**");
    }
}

在线引入bootstrap包

 在eclipse中,本地引入一直引入不起,绝对路径和相对路径都不行~所以,现在就先用在线包引入bootstrap。同时bootstrap需要jquery来支持

 <link rel="stylesheet" href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css">  
   <script src="http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js"></script>
   <script src="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/js/bootstrap.min.js"></script>

员工列表展示

1.提取公共页面

dashboard.html
<div th:fragment="bottom">这是底部消息</div>     //要提取的部分

list.html 
<div th:insert="~{dashboard::bottom}"></div>  //插入进去


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

2.列表循环展示

dashboard.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
[[${session.loginUser}]]
<h1>dashboard</h1>
    
//前端点击
<a th:href="@{/emps}">员工管理</a>

<div th:fragment="bottom">这是底部消息</div>
</body>
</html>

controller

@Controller
public class EmployeeController {
    @Autowired
    EmployeeDao employeeDao;

    @RequestMapping("/emps")
    public String list(Model model){
        Collection<Employee> employee = employeeDao.getAll();
        model.addAttribute("emps",employee);
        return "emps/list";
    }
}

list.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>

 <link rel="stylesheet" href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<body>
<table class="table table-bordered">
    <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>[[${emp.getLastName()}]]</td>
    <td th:text="${emp.getEmail()}"></td>
    <td th:text="${emp.getGender()==0?'':''}"></td>
    <td th:text="${emp.department.getDepartmentName()}"></td>
    <td th:text="${#dates.format(emp.getBirth(),'yyyy-MM-dd HH:mm:ss')}"></td>
    <td>
        <button class="btn btn-sm btn-primary">编辑</button>
        <button class="btn btn-sm btn-danger">删除</button>

    </td>
</tr>
    </tbody>
</table>

<div th:insert="~{dashboard::bottom}"></div>
</body>
</html>

增加员工实现

1.先来个添加按钮

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

2.controller

  • 注意和下面的请求一样,但是一个是get一个是post
 @GetMapping("/emp")
    public String toAddpage(Model model){
      //  System.out.println(1);
        //查出所有部门的信息
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("department",departments);
        return  "emps/add";
    }

3.添加页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>

 <link rel="stylesheet" href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<body>



<form th:action="@{/emp}" method="post">
    <div class="form-group">
        <label>LastName</label>
        <input type="text" name="lastName" class="form-control" placeholder="kuangshen"></div>
    <div class="form-group">
        <label>Email</label>
        <input type="email"  name="email" class="form-control" placeholder="24736743eqq.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-labe1"></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">
<!--       我们在controller接收的是一个Empolyee,所以我们需要提交的是其中的一个属性!     -->
            <option th:each="dept:${department}" th:text="${dept.getDepartmentName()}" th:value="${dept.getId()}"></option>

        </select>
    </div>
            <div class="form-group">
                <label>Birth</label>
                <input name="birth" type="text" class="form-control" placeholder="kuangstudy">
            </div>
            <button type="submit" class="btn btn-primary">添加</button>
</form>
</body>
</html>
  • 注意点:
    <form th:action="@{/emp}" method="post">
        
     -----------------------------------------------
    
        <div class="form-group">
            <label>department</label>
            <select class="form-control" name="department.id">
    <!--       我们在controller接收的是一个Empolyee,所以我们需要提交的是其中的一个属性!     -->
                <option th:each="dept:${department}" th:text="${dept.getDepartmentName()}" th:value="${dept.getId()}"></option>
    
            </select>
        </div>
    
  • #时间日期格式化
    spring.mvc.format.date=yyyy-MM-dd
    

4.提交的请求controller

  @PostMapping("/emp")
    public String addEmp(Employee employee){
       // System.out.println(employee);
        employeeDao.save(employee);
     return  "redirect:/emps";
    }

修改员工信息

1.跳转到修改页面html

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

2.跳转到修改页面controller

  //去员工的修改页面
    @GetMapping("/emp/{id}")
    public String toUpdateEmp(@PathVariable("id")Integer id,Model model){
        //查出原来的数据
        Employee employee = employeeDao.getEmployeeById(id);
        model.addAttribute("emp",employee);
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("department",departments);
        return "emps/update";
    }

3.修改页面update.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>

 <link rel="stylesheet" href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<body>



<form th:action="@{/updateEmp}" 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="kuangshen"></div>
    <div class="form-group">
        <label>Email</label>
        <input th:value="${emp.getEmail()}" type="email"  name="email" class="form-control" placeholder="24736743eqq.com"></div>
    <div class="form-group">
        <label>Gender</label><br/>
    <div class="form-check form-check-inline">
    <input th:checked="${emp.getGender()==1}" class="form-check-input" type="radio" name="gender"
           value="1">
        <label class="form-check-labe1"></label>
    </div>
    <div class="form-check form-check-inline">
        <input th:checked="${emp.getGender()==0}" 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">
<!--       我们在controller接收的是一个Empolyee,所以我们需要提交的是其中的一个属性!     -->
            <option th:selected="${dept.getId()==emp.getDepartment().id}"
                    th:each="dept:${department}" th:text="${dept.getDepartmentName()}" th:value="${dept.getId()}"></option>

        </select>
    </div>
            <div class="form-group">
                <label>Birth</label>
                <input th:value="${#dates.format(emp.getBirth(),'yyyy-MM-dd HH:mm:ss')}" name="birth" type="text" class="form-control" placeholder="kuangstudy">
            </div>
            <button type="submit" class="btn btn-primary">修改</button>
</form>
</body>
</html>

4.保存提交请求controller

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

删除员工

前端删除请求

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

后端接收请求

 @GetMapping("/delemp/{id}")
    //删除员工
    public String delEmp(@PathVariable("id")Integer id){
        employeeDao.delete(id);
        return "redirect:/emps";
    }

404页面

只要在templates下面建个error文件夹,把404.html放在里面,自动会扫描到

注销功能

前端请求

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

后端接收请求

 //注销
    @RequestMapping("/user/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "redirect:/index.html";
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值