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. 讓這個網站能夠獨立運行


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM