7

SpringMVC:RESTful案例 - 愚生浅末

 2 years ago
source link: https://www.cnblogs.com/kohler21/p/17155491.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

SpringMVC:RESTful案例 - 愚生浅末 - 博客园

和传统 CRUD 一样,实现对员工信息的增删改查。

  • 准备实体类
public class Employee {
    private Integer id;
    private String lastName;
    private String email;
    //1 male, 0 female
    private Integer gender;
    //getter,setter,有参无参
}
  • 准备dao模拟数据
@Repository
public class EmployeeDao {
    private static Map<Integer, Employee> employees = null;
    static{
        employees = new HashMap<Integer, Employee>();
        employees.put(1001, new Employee(1001, "E-AA", "[email protected]", 1));
        employees.put(1002, new Employee(1002, "E-BB", "[email protected]", 1));
        employees.put(1003, new Employee(1003, "E-CC", "[email protected]", 0));
        employees.put(1004, new Employee(1004, "E-DD", "[email protected]", 0));
        employees.put(1005, new Employee(1005, "E-EE", "[email protected]", 1));
    }
    private static Integer initId = 1006;
    public void save(Employee employee){
        if(employee.getId() == null){
            employee.setId(initId++);
        }
        employees.put(employee.getId(), employee);
    }
    public Collection<Employee> getAll(){
        return employees.values();
    }
    public Employee get(Integer id){
        return employees.get(id);
    }
    public void delete(Integer id){
        employees.remove(id);
    }
}
功能 URL 地址 请求方式
访问首页√ / GET
查询全部数据√ /employee GET
删除√ /employee/2 DELETE
跳转到添加数据页面√ /toAdd GET
执行保存√ /employee POST
跳转到更新数据页面√ /employee/2 GET
执行更新√ /employee PUT

具体功能:访问首页

①配置view-controller

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

②创建页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8" >
        <title>Title</title>
    </head>
    <body>
        <h1>首页</h1>
        <a th:href="@{/employee}">访问员工信息</a>
    </body>
</html>

具体功能:查询所有员工数据

①控制器方法

@RequestMapping(value = "/employee", method = RequestMethod.GET)
public String getEmployeeList(Model model){
    Collection<Employee> employeeList = employeeDao.getAll();
    model.addAttribute("employeeList", employeeList);
    return "employee_list";
}

②创建employee_list.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Employee Info</title>
        <script type="text/javascript" th:src="@{/static/js/vue.js}"></script>
    </head>
    <body>
        <table border="1" cellpadding="0" cellspacing="0" style="text-align:center;" id="dataTable">
            <tr>
                <th colspan="5">Employee Info</th>
            </tr>
            <tr>
                <th>id</th>
                <th>lastName</th>
                <th>email</th>
                <th>gender</th>
                <th>options(<a th:href="@{/toAdd}">add</a>)</th>
            </tr>
            <tr th:each="employee : ${employeeList}">
                <td th:text="${employee.id}"></td>
                <td th:text="${employee.lastName}"></td>
                <td th:text="${employee.email}"></td>
                <td th:text="${employee.gender}"></td>
                <td>
                    <a class="deleteA" @click="deleteEmployee"
                       th:href="@{'/employee/'+${employee.id}}">delete</a>
                    <a th:href="@{'/employee/'+${employee.id}}">update</a>
                </td>
            </tr>
        </table>
    </body>
</html>

具体功能:删除

①创建处理delete请求方式的表单

<!-- 作用:通过超链接控制表单的提交,将post请求转换为delete请求 -->
<form id="delete_form" method="post">
    <!-- HiddenHttpMethodFilter要求:必须传输_method请求参数,并且值为最终的请求方式 -->
    <input type="hidden" name="_method" value="delete"/>
</form>

引入vue.js

<script type="text/javascript" th:src="@{/static/js/vue.js}"></script>

删除超链接

<a class="deleteA" @click="deleteEmployee"th:href="@{'/employee/'+${employee.id}}">delete</a>

通过vue处理点击事件

<script type="text/javascript">
    var vue = new Vue({
        el:"#dataTable",
        methods:{
            //event表示当前事件
            deleteEmployee:function (event) {
                //通过id获取表单标签
                var delete_form = document.getElementById("delete_form");
                //将触发事件的超链接的href属性为表单的action属性赋值
                delete_form.action = event.target.href;
                //提交表单
                delete_form.submit();
                //阻止超链接的默认跳转行为
                event.preventDefault();
            }
        }
    });
</script>

③控制器方法

@RequestMapping(value = "/employee/{id}", method = RequestMethod.DELETE)
public String deleteEmployee(@PathVariable("id") Integer id){
    employeeDao.delete(id);
    return "redirect:/employee";
}

具体功能:跳转到添加数据页面

①配置view-controller

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

②创建employee_add.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Add Employee</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="add"><br>
        </form>
    </body>
</html>

具体功能:执行保存

①控制器方法

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

具体功能:跳转到更新数据页面

①修改超链接

<a th:href="@{'/employee/'+${employee.id}}">update</a>

②控制器方法

@RequestMapping(value = "/employee/{id}", method = RequestMethod.GET)
public String getEmployeeById(@PathVariable("id") Integer id, Model model){
    Employee employee = employeeDao.get(id);
    model.addAttribute("employee", employee);
    return "employee_update";
}

③创建employee_update.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Update Employee</title>
    </head>
    <body>
        <form th:action="@{/employee}" method="post">
            <input type="hidden" name="_method" value="put">
            <input type="hidden" name="id" th:value="${employee.id}">
            lastName:<input type="text" name="lastName" th:value="${employee.lastName}">
            <br>
            email:<input type="text" name="email" th:value="${employee.email}"><br>
            <!--
                th:field="${employee.gender}"可用于单选框或复选框的回显
                若单选框的value和employee.gender的值一致,则添加checked="checked"属性
			-->
            gender:<input type="radio" name="gender" value="1"th:field="${employee.gender}">male
            <input type="radio" name="gender" value="0"th:field="${employee.gender}">female<br>
            <input type="submit" value="update"><br>
        </form>
    </body>
</html>

具体功能:执行更新

控制器方法

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

欢迎关注公众号:愚生浅末。

__EOF__


Recommend

  • 49

    一、理解RESTREST(RepresentationalStateTransfer),中文翻译叫“表述性状态转移”。是RoyThomasFielding在他2000年的博士论文中提出的。它与传统的SOAPWeb服务区别在于,REST关注的是要处理的数据,而SOAP主要关注行为和处理。要理解好REST,根据其首字母拆分出的...

  • 8

    Java-GUI编程之处理位图 - 愚生浅末 - 博客园 如果仅仅绘制一些简单的几何图形,程序的图形效果依然比较单调 。 AWT 也允许在组件上绘制位图, Graphics 提供了 drawlmage() 方法用于绘制位图,该方法需要一个Image参数一一代表位图,通过该方法就可 以...

  • 12

    VSCode开发环境配置 先到VSCode官网去下载适合自己系统的VSCode安装软件 VScode下载地址:ht...

  • 2

    为组件设置边框 很多情况下,我们常常喜欢给不同的组件设置边框,从而让界面的层次感更明显,swing中提供了Border对象来代表一个边框,下图是Border的继承体系图: 特殊的Border: TitledBorder:...

  • 8
    • www.cnblogs.com 2 years ago
    • Cache

    Java String类 - 愚生浅末

     字符串广泛应用 在 Java 编程中,在 Java 中字符串属于对象,Java 提供了 String 类来创建和操作字符串。 jdk中提供非常多的字符和字符串操作方法及构造方法,这里只介绍一些常用的方法和构造方法。完整的String类下的方法可以参考官方的API文档。 本地...

  • 5
    • www.cnblogs.com 2 years ago
    • Cache

    HTTP 协议概述 - 愚生浅末

    什么是 HTTP 协议 什么是协议? 协议是指双方,或多方,相互约定好,大家都需要遵守的规则,叫协议。 所谓 HTTP 协议,就是指,客户端和服务器之间通信时,发送的数据,需要遵守的规则,叫 HTTP 协议。 HTTP 协议中...

  • 11

    How to code like a pro in 2022 and avoid If-Else

  • 9
    • www.cnblogs.com 2 years ago
    • Cache

    Java中的命名规则 - 愚生浅末

    Java中的命名规则 在查找java命名规则时,未在国内相关网站查找到较为完整的文章,这是一篇国外程序开发人员写的java命名规则的文章,原文是英文写的,为了便于阅读,遂翻译为汉语,以便帮助国内开发者有所了解。

  • 12

    雷军传-怀揣梦想,砥砺前行

  • 9

    "xxx cannot be cast to jakarta.servlet.Servlet "报错解决方式 ...

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK