导读 这篇文章主要为大家介绍了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(添加)< /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="添加">
< /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实现添加功能的详细内容

原文来自:https://www.jb51.net/article/249696.htm

本文地址:https://www.linuxprobe.com/springmvc-restful-linux.html编辑:倪家兴,审核员:逄增宝

Linux命令大全:https://www.linuxcool.com/

Linux系统大全:https://www.linuxdown.com/

红帽认证RHCE考试心得:https://www.rhce.net/