java-springboot简单易学的员工管理系统

本文介绍了使用 Spring Boot 搭建简单应用的过程,包括资源导入、POJO 类定义、模拟数据库操作、DAO 层实现、首页配置、页面国际化、自定义 MVC 配置、登录拦截器以及增删改查功能的实现。通过 Thymeleaf 模板引擎进行页面展示,并提供了登录页面的国际化。在实际运行中遇到了Thymeleaf表达式解析错误、日期格式问题以及自增ID的问题,并给出了相应的解决方案。
摘要由CSDN通过智能技术生成

1.导入资源

2.编写相应的pojo

3.模拟数据库,编写dao层

4.首页配置:

5.页面国际化:

6.编写MyMvcConfig

7.登录+拦截器

8.增删改查


1.导入资源

链接:https://pan.baidu.com/s/1LrnF3RPqnt4A2pzTFU5B_g 
提取码:zzxc

2.编写相应的pojo

导入lombok依赖

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
//员工表
@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();
    }
}
//部门表
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Department {
    private int id;  //部门id
    private String departmentName;  //部门名字
}

3.模拟数据库,编写dao层

package com.kun.dao;

import com.kun.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<>();   //创建部门表
        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 idd){
        return departments.get(idd);
    }
}
package com.kun.dao;

import com.kun.pojo.Department;
import com.kun.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","140@qq.com",1,new Department(101,"教学部")));
        employees.put(1002,new Employee(1002,"BB","1402@qq.com",1,new Department(102,"市场部")));
        employees.put(1003,new Employee(1003,"CC","14024@qq.com",1,new Department(103,"教研部")));
        employees.put(1004,new Employee(1004,"DD","140240@qq.com",1,new Department(104,"运营部")));
        employees.put(1005,new Employee(1005,"EE","1402401@qq.com",1,new Department(105,"后勤部")));
    }
//    增加员工
    private static Integer initId=1006;

    public void save(Employee employee){
        if (employee.getId()==null){
            employee.setId(initId++);
        }
        employee.setDepartment(departmentDao.getDepartmentById(employee.getDepartment().getId()));

        employees.put(employee.getId(),employee);
    }
    //    获取所有员工信息
    public Collection<Employee> getEmployees(){
        return employees.values();
    }
    //    根据id
    public Employee getEmployeeById(Integer id){
        return employees.get(id);
    }
//    删除员工
    public void delete(Integer id){
        employees.remove(id);
    }


}

4.首页配置:

        1.用thymeleaf接管    url 用@

导入依赖

<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>

5.页面国际化:

建立一个login.properties文件,还有一个login_zh_CN.properties;发现IDEA自动识别了我们要做国际化操作

在properties配置文件中配置
spring.messages.basename=i18n.login

package com.kun.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 l = request.getParameter("l");
        Locale aDefault = Locale.getDefault();
        if(!StringUtils.isEmpty(l)){
            String[] s = l.split("_");
            aDefault = new Locale(s[0], s[1]);
        }
        return aDefault;
    }
    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
    }
}

<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>

6.编写MyMvcConfig

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

@Configuration
public class MyMvc 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();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginHandlerInterceptor()).
                addPathPatterns("/**").excludePathPatterns("/index.html","/","/user/login","static/**");
    }

}

7.登录+拦截器

页面存在缓存,所以我们需要禁用模板引擎的缓存

<form class="form-signin" th:action="@{/user/login}" method="post">
 //这里面的所有表单标签都需要加上一个name属性 
    
</form>
@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";
        }
    }
}

拦截器

package com.kun.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 {
        Object loginUser = request.getSession().getAttribute("LoginUser");
        if (loginUser==null){
            request.setAttribute("msg","没有权限");
            request.getRequestDispatcher("/index.html").forward(request,response);
            return false;
        }else {
            return true;
        }
    }
}
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginHandlerInterceptor()).
                addPathPatterns("/**").excludePathPatterns("/index.html","/","/user/login","static/**");
    }

8.增删改查

package com.kun.controller;

import com.kun.dao.DepartmentDao;
import com.kun.dao.EmployeeDao;
import com.kun.pojo.Department;
import com.kun.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Collection;

@Controller
public class EmployeeController {
    @Autowired
    EmployeeDao employeeDao;
    @Autowired
    DepartmentDao departmentDao;

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

    @GetMapping("/emp")
    public String toAdd(Model model){
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("departments",departments);
        return "emp/add";
    }
    @PostMapping ("/emp")
    public String addEmp(Employee employee){
        //保存员工的信息
        System.out.println(employee);
        employeeDao.save(employee);
        return "redirect:/emps";
    }
    @RequestMapping("/emp/{id}")
    public String toUpdate(@PathVariable("id")Integer id,Model model){
        Employee employee = employeeDao.getEmployeeById(id);
        model.addAttribute("emp",employee);
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("departments",departments);
        return "emp/update";
    }

    @RequestMapping("/delEmp/{id}")
    public String delete(@PathVariable("id")Integer id){
        employeeDao.delete(id);
        return "redirect:/emps";
    }

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

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

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

				<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
					<h2><a class="btn btn-sm btn-success" th:href="@{/emp}">添加员工</a></h2>
					<div class="table-responsive">
						<table class="table table-striped table-sm">
							<thead>
								<tr>
									<th>id</th>
									<th>lastName</th>
									<th>email</th>
									<th>gender</th>
									<th>department</th>
									<th>birth</th>
								</tr>
							</thead>
							<tbody>
								<tr th:each="emp:${emps}">
									<td th:text="${emp.getId()}"></td>
									<td th:text="${emp.getLastName()}"></td>
									<td th:text="${emp.getEmail()}"></td>
									<td th:text="${emp.getGender()==0?'女':'男'}"></td>
									<td th:text="${emp.department.getDepartmentName()}"></td>
									<td th:text="${#dates.format(emp.getBirth(),'yyyy-MM-dd HH:mm:ss')}"></td>
									<td>
										<a class="btn btn-sm btn-primary" th:href="@{/emp/}+${emp.getId()}">编辑</a>
										<a class="btn btn-sm btn-danger"  th:href="@{/delEmp/}+${emp.getId()}">删除</a>
									</td>
								</tr>
							</tbody>
						</table>
					</div>
				</main>
			</div>
		</div>

增加员工的表单

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

修改员工的表单

<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()}" class="form-control" placeholder="kuangshen" type="text" name="lastName">
						</div>
						<div class="form-group" ><label>Email</label>
							<input th:value="${emp.getEmail()}" class="form-control" placeholder="24736743@qq.com" type="email" name="email">
						</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" name="gender" type="radio" value="1">
								<label class="form-check-label">男</label>
							</div>
							<div class="form-check form-check-inline">
								<input th:checked="${emp.getGender()==0}" class="form-check-input" name="gender" type="radio" value="0">
								<label class="form-check-label">女</label>
							</div>
						</div>
						<div class="form-group" ><label>department</label>
							<select class="form-control" name="department.id">
								<option th:selected="${dept.id==emp.getDepartment().getId()}" th:each="dept:${departments}" th:text="${dept.getDepartmentName()}" th:value="${dept.getId()}"></option>
							</select>
						</div>
						<div class="form-group" >
							<label >Birth</label>
							<input th:value="${#dates.format(emp.birth,'yyyy-MM-dd HH:mm')}" class="form-control" placeholder="2021-02-02" type="text" name="birth">
						</div>
						<button class="btn btn-primary" type="submit">修改</button>
					</form>

错误:

问题一:

Caused by: org.attoparser.ParseException: Could not parse as expression: Thymeleaf格式错误

问题二:

插入员工报400错误:日期格式必须为“  / ”  或者  spring.mvc.format.date=yyyy-MM-dd

问题三:

修改员工,因为修改员工id为自增,导致修改员工,id++:解决办法:

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
课程简介:历经半个多月的时间,Debug亲自撸的 “企业员工角色权限管理平台” 终于完成了。正如字面意思,本课程讲解的是一个真正意义上的、企业级的项目实战,主要介绍了企业级应用系统中后端应用权限的管理,其中主要涵盖了六大核心业务模块、十几张数据库表。 其中的核心业务模块主要包括用户模块、部门模块、岗位模块、角色模块、菜单模块和系统日志模块;与此同时,Debug还亲自撸了额外的附属模块,包括字典管理模块、商品分类模块以及考勤管理模块等等,主要是为了更好地巩固相应的技术栈以及企业应用系统业务模块的开发流程! 核心技术栈列表: 值得介绍的是,本课程在技术栈层面涵盖了前端和后端的大部分常用技术,包括Spring BootSpring MVC、Mybatis、Mybatis-Plus、Shiro(身份认证与资源授权跟会话等等)、Spring AOP、防止XSS攻击、防止SQL注入攻击、过滤器Filter、验证码Kaptcha、热部署插件Devtools、POI、Vue、LayUI、ElementUI、JQuery、HTML、Bootstrap、Freemarker、一键打包部署运行工具Wagon等等,如下图所示: 课程内容与收益: 总的来说,本课程是一门具有很强实践性质的“项目实战”课程,即“企业应用员工角色权限管理平台”,主要介绍了当前企业级应用系统中员工、部门、岗位、角色、权限、菜单以及其他实体模块的管理;其中,还重点讲解了如何基于Shiro的资源授权实现员工-角色-操作权限、员工-角色-数据权限的管理;在课程的最后,还介绍了如何实现一键打包上传部署运行项目等等。如下图所示为本权限管理平台的数据库设计图: 以下为项目整体的运行效果截图: 值得一提的是,在本课程中,Debug也向各位小伙伴介绍了如何在企业级应用系统业务模块的开发中,前端到后端再到数据库,最后再到服务器的上线部署运行等流程,如下图所示:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值