SpringMVC passes and receives array or list parameters

When a user triggers a certain request on the page, some parameters (key/value) are usually brought to the background. In SpringMVC, you can bind the key/value data requested by the client to the formal parameters of the Controller processor method through parameter binding.

Sometimes the data requested by the front-end is in batches, and at this time, the web side is required to obtain these batch request parameters when processing the request. Generally, batch request parameters are received in the form of arrays or collections in Java, and SpringMVC provides a mechanism for receiving and parsing data and collection parameter types.

Recommended article: "SpringMVC request parameter binding and the use of @RequestParam annotation"

1. Request parameters of array type 

For the request parameters of the array type, a checkbox-like form may appear on the HTML page, allowing the user to select one or more data for operation.

[Example] To implement the batch delete function, select one or more user information through the check box in the HTML page and submit it to the background. The method in the background Controller controller obtains the request parameters of the array type.

(1) Create an HTML page, select one or more user information through the check box, and submit it to the background.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>数组类型的请求参数</title>
    <meta name="author" content="pan_junbiao的博客">
    <style>
        table { border-collapse: collapse;}
        table,table tr th, table tr td { border:1px solid #000000; text-align: center; padding: 5px;}
        .u_button{padding: 5px; margin-top: 10px;}
    </style>
</head>
<body>
<body>
<table>
    <tr>
        <th><input type="checkbox" id="checkAll" /></th>
        <th>编号</th>
        <th>用户名称</th>
        <th>博客信息</th>
    </tr>
    <tr>
        <td><input type="checkbox" name="checkItem" value="1"/></td>
        <td>1</td>
        <td>pan_junbiao的博客</td>
        <td>您好,欢迎访问 pan_junbiao的博客</td>
    </tr>
    <tr>
        <td><input type="checkbox" name="checkItem" value="2"/></td>
        <td>2</td>
        <td>pan_junbiao的博客</td>
        <td>https://blog.csdn.net/pan_junbiao</td>
    </tr>
    <tr>
        <td><input type="checkbox" name="checkItem" value="3"/></td>
        <td>3</td>
        <td>pan_junbiao的博客</td>
        <td>您好,欢迎访问 pan_junbiao的博客</td>
    </tr>
    <tr>
        <td><input type="checkbox" name="checkItem" value="4"/></td>
        <td>4</td>
        <td>pan_junbiao的博客</td>
        <td>https://blog.csdn.net/pan_junbiao</td>
    </tr>
    <tr>
        <td><input type="checkbox" name="checkItem" value="5"/></td>
        <td>5</td>
        <td>pan_junbiao的博客</td>
        <td>您好,欢迎访问 pan_junbiao的博客</td>
    </tr>
</table>
<input type="button" class="u_button" value="反选" id="btnCheckedRev"/>
<input type="button" class="u_button" value="批量删除" id="btnBatchDelete"/>
</body>
</body>
<script src="/js/jquery-3.4.1.min.js"></script>
<script>
    $(document).ready(function() {
        //全选
        $("#checkAll").click(function () {
            $("[name=checkItem]:checkbox").prop("checked", this.checked);
        });

        //复选框组的联动效果
        $("[name=checkItem]:checkbox").click(function () {
            var flag = true;
            $("[name=checkItem]:checkbox").each(function () {
                if (!this.checked) {
                    flag = false;
                }
            });
            $("#checkAll").prop("checked", flag);
        });

        //反选
        $("#btnCheckedRev").click(function () {
            $("[name=checkItem]:checkbox").each(function () {
                this.checked = !this.checked;
            });
        });

        //批量删除事件
        $("#btnBatchDelete").click(function () {
        let idArray = new Array(); //批量删除的员工ID数组
        $("[name=checkItem]:checkbox:checked").each(function (index) {
            idArray.push($(this).val());
        });

        if (idArray.length == 0) {
            alert("请选择要删除的用户!");
            return;
        }

        if (!confirm("确定删除记录吗?")) {
            return;
        }

        //执行Ajax请求
        $.ajax({
            type: "POST",
            url: "/user/batchDeleteUser",
            data: {userIds: idArray},
            success: function (result) {
                if (result == true) {
                    alert("删除成功");
                }
                else {
                    alert("删除失败");
                }
            }
        });
    });
});
</script>
</html>

Page execution result:

(2) Write the execution method in the Controller to obtain the request parameters of the array type.

/**
 * 批量删除用户信息
 * @param userIds 数组
 * @author pan_junbiao
 */
@RequestMapping("/batchDeleteUser")
@ResponseBody
public boolean batchDeleteUser(@RequestParam(value="userIds[]") Integer[] userIds)
{
    //参数验证
    if (userIds == null || userIds.length == 0)
    {
        return false;
    }

    //打印数组
    System.out.println("用户编号:");
    Arrays.stream(userIds).forEach(System.out::println);

    //执行后台批量删除(忽略代码)
    return true;
}

Note: The @RequestParam(value="userIds[]") statement must be added to the parameter declaration of the background controller method, otherwise the submitted user ID array cannot be obtained.

The console output: 

 

2. List type request parameters

List type request parameter. When you want to convert the batch data on the page into a List type object on the Web side through SpringMVC, the processor adapter will convert the format and parse the request parameters into the corresponding List collection.

[Example] To realize the batch addition function, the front-end HTML page submits multiple pieces of user information, and the method in the back-end Controller controller obtains the request parameters of the List type.

(1) Create an HTML page and submit multiple pieces of user information to the background Controller.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>List类型的请求参数</title>
    <meta name="author" content="pan_junbiao的博客">
    <style>
        .u_button{padding: 5px; margin-top: 10px;}
    </style>
</head>
    <input type="button" class="u_button" value="批量新增" id="btnBatchAdd"/>
<body>
</body>
<script src="/js/jquery-3.4.1.min.js"></script>
<script>
    $(document).ready(function()
    {
        //批量删除事件
        $("#btnBatchAdd").click(function() {
            //创建用户列表
            let userList = [];
            userList.push({userId: 1, userName: "pan_junbiao的博客", blogRemark: "您好,欢迎访问 pan_junbiao的博客"});
            userList.push({userId: 2, userName: "pan_junbiao的博客", blogRemark: "https://blog.csdn.net/pan_junbiao"});
            userList.push({userId: 3, userName: "pan_junbiao的博客", blogRemark: "您好,欢迎访问 pan_junbiao的博客"});
            userList.push({userId: 4, userName: "pan_junbiao的博客", blogRemark: "https://blog.csdn.net/pan_junbiao"});
            userList.push({userId: 5, userName: "pan_junbiao的博客", blogRemark: "您好,欢迎访问 pan_junbiao的博客"});

            //执行Ajax请求
            $.ajax({
                type: "POST",
                url: "/user/batchAddUser",
                dataType: "json",
                contentType: "application/json; charset=UTF-8",
                data: JSON.stringify(userList), //转换为JSON
                success: function (result) {
                    if (result == true) {
                        alert("新增成功");
                    }
                    else {
                        alert("新增失败");
                    }
                }
            });
        });
    });
</script>
</html>

(2) Create a user information entity class (UserInfo.java).

package com.pjb.entity;

/**
 * 用户信息实体类
 * @author pan_junbiao
 **/
public class UserInfo
{
    private int userId; //用户编号
    private String userName; //用户姓名
    private String blogRemark; //博客信息

    //省略getter与setter方法...

    @Override
    public String toString()
    {
        return "编号:" + this.userId + "  用户:" + this.userName +  "  博客:" + this.blogRemark;
    }
}

(3) Write the execution method in the Controller to obtain the request parameters of the List type.

/**
 * 批量新增用户信息
 * @param userInfoList 列表
 * @author pan_junbiao
 */
@RequestMapping("/batchAddUser")
@ResponseBody
public boolean batchAddUser(@RequestBody List<UserInfo> userInfoList)
{
    //参数验证
    if (userInfoList == null || userInfoList.size()==0)
    {
        return false;
    }

    //打印数组
    System.out.println("用户列表:");
    userInfoList.stream().forEach(System.out::println);

    //执行后台批量新增(忽略代码)
    return true;
}

Note: The @RequestBody annotation must be added to the parameter declaration of the background controller method. The characteristic of the @RequestBody annotation is that it determines whether to convert the relevant format to the packaging class according to the Content-Type of the request parameter. If the Content-Type is the target type, Just convert. What is converted here is JSON data, and all requirements are to specify the Content-Type of the front-end request as "application/json".

The console output: 

 

Guess you like

Origin blog.csdn.net/pan_junbiao/article/details/109778471