好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

SpringMVC实战案例RESTFul实现添加功能

RESTFul实现添加功能

数据被删除差不多了,得做个添加的功能。

一、前端改动

1. 修改列表页,增加一个【添加】按钮

点击这个按钮可以调到新增页面。

<tr>
          <th colspan="5">员工列表</th>
      </tr>
      <tr>
          <th>id</th>
          <th>lastName</th>
          <th>email</th>
          <th>gender</th>
          <th>options(<a th:href="@{/toAdd}" rel="external nofollow" >添加</a>)</th>
      </tr>
2. 配置 view-controller

因为/toAdd这个跳转仅仅是视图的跳转,所以可以直接在 springMVC 配置文件中配置 view-controller:

<mvc:view-controller path="/toAdd" view-name="employee_add"></mvc:view-controller>

视图名字就叫employee_add,那么对应地需要增加一个 employee_add.html页面。

3. 编写添加页面

新建 employee_add.html:

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

<form th:action="@{/employee}" method="post">
  lastName:<input type="text" name="lastName"><br>
  email:<input type="text" name="email"><br>
  gender:<input type="radio" name="gender" value="1">male
  <input type="radio" name="gender" value="0">female<br>
  <input type="submit" value="添加"><br>
</form>

</body>
</html>

action 里的路径/employee,就是要访问的地址了,因为添加本来就是要用 post 方法,所以这里不用想之前 delete 方法那样转换了。

二、后端处理

到 EmployeeController 控制器类里,新增一个处理添加请求的方法:

@RequestMapping(value = "/employee", method = RequestMethod.POST)
  public String addEmployee(Employee employee) {
      employeeDao.save(employee);
      return "redirect:/employee";
  }

这里使用 实体类传参,然后调用 dao 里的 save() 方法即可,返回依然是重定向到列表页。

三、测试效果

重新部署,访问列表页。

数据又是 5 条了,因为重新部署了,初始化了。

点击【添加】按钮,打开添加页面,添加一个员工:

点击添加成功后,跳转到列表页,展示添加后的结果:

以上就是SpringMVC实战案例RESTFul实现添加功能的详细内容,更多关于SpringMVC RESTFul添加的资料请关注其它相关文章!

原文链接:https://blog.csdn.net/wessonlan/article/details/124812943

查看更多关于SpringMVC实战案例RESTFul实现添加功能的详细内容...

  阅读:12次