springboot_数据增删改查

1、员工列表展示

  • thymeleaf提取公共页面
    • 提取:th:fragment="sidebar"
    • 插入:<div th:replace="~{commons/commons::sidebar}"></div>
      或者<div th:insert="~{commons/commons::sidebar}"></div>
    • 如果传递参数:使用():
      <div th:insert="~{commons/commons::sidebar(active='main.html')}"></div>
    • 接收判断:
      <a th:class="${active=='main.html'?'nav-link active':'nav-link'}" th:href="@{/index.html}">
  • 列表循环展示
    • Controller返回前端数据:
      @Controller
      public class EmployeeController {
          @Autowired
          EmployeeDao employeeDao;
      
          @RequestMapping("/emps")
          public String list(Model model){
              Collection<Employee> employees = employeeDao.getAllEmployee();
              model.addAttribute("emps",employees);
              return "emp/list";
          }
      }
      
    • 遍历循环:
      <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.getDepartment().getDepartmentName()}"></td>
          <td th:text="${#dates.format(emp.getBirth(),'yyyy-MM-dd HH:mm:ss')}"></td>
      </tr>
      

2、添加员工

  • 提交按钮
    <!-- 设置action,进入对应的controller  请求方法:post -->
    <form th:action="@{/emp}" method="post">
    
    //进入@PostMapping的controller
    @PostMapping("/emp")
    public String addEmp(Employee employee){
        System.out.println(employee);
        employeeDao.add(employee);
        return "redirect:/emps";
    }
    
  • 跳转到添加页面
    <!-- 点击添加添加员工,进行页面跳转 -->
    <h2><a class="btn btn-sm btn-success" th:href="emp">添加员工</a></h2>
    
    //对应的controller,@GetMapping,此controller进行页面的跳转
    //model设置departments参数返回前端显示
    @GetMapping("/emp")
    public String toAddPage(Model model){
        Collection<Department> department = departmentDao.getDepartment();
        model.addAttribute("departments",department);
        return "emp/add";
    }
    
      <!-- 前端遍历departments进行显示 -->
      <select class="form-control" name="department.id">
          <option th:each="dept:${departments}" th:text="${dept.getDepartmentName()}" th:value="${dept.getId()}"></option>
      </select>
    
  • 添加员工成功
  • 返回首页
    @PostMapping("/emp")
        public String addEmp(Employee employee){
            System.out.println(employee);
            employeeDao.add(employee);
            //重定向到员工信息页面,
            return "redirect:/emps";
        }
    
    //跳转到对应这,返回list页面。
    @RequestMapping("/emps")
    public String list(Model model){
    Collection<Employee> employees = employeeDao.getAllEmployee();
    model.addAttribute("emps",employees);
    return "emp/list";
    }
    
上一篇:jq实现发送验证码倒计时60s


下一篇:EL表达式