• Springboot 员工管理系统


    准备工作

    将资源放到对应的文件夹

    java 模拟数据库

    Department.java 部门实体类

    //部门表
    @Data
    @NoArgsConstructor //无参构造器
    @AllArgsConstructor //有参构造器
    public class Department {
    
        private Integer id;
        private String departmentName;
    }
    

    Employee.java 员工实体类

    //员工表
    @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();
        }
    }
    

    DepartmentDao.java

    //部门dao
    @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.java

    //员工dao
    @Repository
    public class EmployeeDao {
        //模拟数据库中的数据
        private static Map<Integer,Employee> employees = null;
        //员工有所属的部门
        @Autowired
        private DepartmentDao departmentDao;
        static {
            //创建部门表
            employees = new HashMap<Integer,Employee>();
    
            employees.put(101,new Employee(1001,"AA","A6131313@qq.com",1,new Department(101,"教学部")));
            employees.put(102,new Employee(1002,"BB","B6131313@qq.com",0,new Department(102,"市场部")));
            employees.put(103,new Employee(1003,"CC","C6131313@qq.com",1,new Department(103,"教研部")));
            employees.put(104,new Employee(1004,"DD","D4234524@qq.com",0,new Department(104,"运营部")));
            employees.put(105,new Employee(1005,"EE","E6131313@qq.com",1,new Department(105,"后勤部")));
        }
    
        //===增删改查===
    
        //主键自增
        private static Integer initId = 1006;
        //增加一个员工
        public void add(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);
        }
    
        //通过id删除员工
        public void delete(Integer id){
            employees.remove(id);
        }
    }
    

    首页实现

    注意点:

    1. 所有页面的静态资源都需要使用 thymeleaf 接管
    2. url:@{}

    com.peng.config/MyMvcConfig.java 配置主页

    @Configuration
    public class MyConfig implements WebMvcConfigurer {
    
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            registry.addViewController("/").setViewName("index");
            registry.addViewController("/index.html").setViewName("index");
        }
    }
    

    页面国际化

    注意点:

    1. 我们需要配置 i18n 文件
    2. 我们如果需要在项目中进行按钮自动切换,我们需要自定义一个组件 LocaleResolver
    3. 记得将自己写的组件配置到spring容器 @Bean
    4. #{}

    利用 bundle 可视化可同时配置几个文件,并在 application.yaml 配置

    #我们的配置文件放在的真实位置
    spring:
      messages:
        basename: i18n.login
    

    首页按钮链接改成 thymeleaf 的语法

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

    MyLocaleResolver.java 自己写的地区解析器

    public class MyLocaleResolver implements LocaleResolver {
    
        //解析请求
        @Override
        public Locale resolveLocale(HttpServletRequest httpServletRequest) {
    
            //获取请求中的语言参数链接
            String language = httpServletRequest.getParameter("l");
            Locale locale = Locale.getDefault(); //如果没有就使用默认的
    
            //如果请求的链接携带了国际化的参数
            if (! StringUtils.isEmpty(language)){
                //zh_CN
                String[] split = language.split("_");
                //国家,地区
                locale = new Locale(split[0], split[1]);
            }
            return locale;
        }
    
        //这里用不上,但不实现接口中这个类会报错
        @Override
        public void setLocale(HttpServletRequest httpServletRequest, @Nullable HttpServletResponse httpServletResponse, @Nullable Locale locale) { }
    }
    

    在 com.peng.config/MyConfig.java 配置文件中注册bean

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

    测试结果


    实现登录功能

    LoginController.java 登录控制器
    @RequestParam:将请求参数绑定到你控制器的方法参数上(是springmvc中接收普通参数的注解)

    @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 "dashboard";
            }else {
                //告诉用户,登录失败
                model.addAttribute("msg","用户名或密码错误");
                return "index";
            }
        }
    }
    

    对应的 index.html 主页中插入提醒

    <p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
    

    登录拦截器

    public class LoginHandlerInterceptor implements HandlerInterceptor {
    
        //返回布尔值,是否放行
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            //在陆成功之后,应该有用户的sessoin
            Object loginUser = request.getSession().getAttribute("loginUser");
    
            if (loginUser==null){ //没有登录
                request.setAttribute("msg","没有权限,请先登录");
                request.getRequestDispatcher("/index.html").forward(request,response);
                return false;
            }else {
                return true;
            }
        }
    }
    

    展示员工列表

    1. 提取公共页面
      1. th: fragment="si debar"
      2. th: replace="~{ commons/ commons : : topbar}"
      3. 如果要传递参数,可以直接使用 () 传参,接收判断即可
    2. 列表循环展示

    EmployeeController.java 员工控制器

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

    添加员工实现

    1. 按钮提交
    2. 跳转到添加页面
    3. 添加员工成功
    4. 返回首页

    EmployeeController.java 员工控制器,添加两个方法

        @GetMapping("/emp")
        public String toAddpage(Model model){
            //查出所有部门的信息
            Collection<Department> departments = departmentDao.getDepartments();
            model.addAttribute("departments",departments);
            return "emp/add";
        }
    
        @PostMapping("/emp")
        public String addEmp(Employee employee){
            System.out.println("save => "+employee);
            //调川底层业务方法保存员工信息
            employeeDao.add(employee);
            return "redirect:emps";
        }
    

    修改员工实现

    EmployeeController.java 员工控制器,又添加两个方法

    	//去员工的修改页面
        @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("departments",departments);
            return "emp/update";
        }
    
        @PostMapping("/updateEmp")
        public String updateEmp(Employee employee){
            employeeDao.add(employee); //修改
            return "redirect:/emps";
        }
    

    删除员工实现

    EmployeeController.java 员工控制器,又添了一个方法

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

    注销

    在 LoginController 里添加该函数

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

    404

    新建一个error文件夹,放一个 404.html 即可,500 也同理

    写网站步骤

    1. 前端搞定,页面长什么样子,数据
    2. 设计数据库(数据库设计 难点!)
    3. 前端让他能够自动运行,独立化工程
    4. 数据接口如何对接:json,对象 all in one!
    5. 前后端联调测试
    • 注意点

      1. 有一套自己熟悉的后台模板:工作必要,推荐x- admin

      2. 前端界面:至少自己能够通过前端框架,组合出来一个网站页面

        index,about,blog,post,user

      3. 让这个网站能够独立运行

  • 相关阅读:
    (转)classload和class.forname()区别
    (转)HashMap和HashTable源码
    (转)spring 框架介绍
    [Spring入门学习笔记][创建网站URL]
    [spring入门学习笔记][spring的IoC原理]
    [J2EE学习][post,get乱码处理]
    [J2EE框架][Debug]
    [SQL学习笔记][用exists代替全称量词 ]
    [Spring入门学习笔记][Spring Boot]
    [Spring入门学习笔记][maven]
  • 原文地址:https://www.cnblogs.com/peng8098/p/java_23.html
Copyright © 2020-2023  润新知