专业的JAVA编程教程与资源

网站首页 > java教程 正文

前后端处理数组和List参数(前端处理数组的办法)

temp10 2024-10-05 01:03:11 java教程 11 ℃ 0 评论

前后端发送接收数组参数

两种在url之中请求的方式

1.http://localhost:9992/test/array?titles=123&titles=hello

前后端处理数组和List参数(前端处理数组的办法)

2.http://localhost:9992/test/array?titles=123,hello,info,test

// 测试一下这样可以接收数组吗
// http://localhost:9992/test/array?titles=123&titles=hello
// http://localhost:9992/test/array?titles=123,hello,info,test 
@RequestMapping("/test/array")public String testArray(String[] titles) {    
    String info = "";    
    for (String s : titles) {        
        info += s;    
    }    
    return info;
}

前后端发送接收List参数

这种在浏览器之中,必须通过ajax请求来完成请求,或者在postman之中完成请求,普通的方式无法完成这样的请求。

前端的代码可以写成如下的样子,主要其实就是list的模拟,需要把list在发送ajax请求的时候序列化,这点注意一下,其他就没有了

function write_list() {
    let fileName = $('#fileName').val();
    // 模拟输入的一个list
    let students = new Array();
    students.push({ name: "李四", pwd: "123" });
    students.push({ name: "张三", pwd: "332" });

    $.ajax({
        type: "post",
        url: "/write-list",
        data: {
            students: JSON.stringify(students), // 将对象序列化成JSON字符串
            fileName: fileName,
        },
        dataType: "JSON",
        success: function (resp) {
            let resultCode = resp.code;
            if (1 == resultCode) {
                console.log("okay")
            } else {
                console.log("error")
            }
        },
        error: function (error) {
            console.log(error);
        }
    });
}

后端接收的时候,需要使用@RequestBody注解,使用List类型接收即可,参数是放在http请求的body部分的,普通的参数fileName可以放到query参数之中

/**
 * 一次性存放多条数据,list导入
 *
 * @param students
 * @param fileName
 * @return
 * @throws IOException
 */
@PostMapping("write-list")
public String writeList(@RequestBody List<PrimaryStudent> students, String fileName) throws IOException {
    if (null == students) {
        return "数据无效!";
    }
    // 存放路径设置
    String userPath = System.getProperty("user.dir");
    if (!fileName.endsWith(".xls") && !fileName.endsWith(".xlsx")) {
        fileName = fileName + ".xlsx";
    } else {
        fileName = userPath + File.separator + fileName;
    }

    try {
        writeExcelService.writeList(students, fileName);
    } catch (Exception e) {
        return e.getMessage();
    }

    return "导出完成!";
}

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表