简体   繁体   English

如何在 Spring 中发布对象列表?

[英]How to post list of objects in Spring?

I have a method in a controller我在 controller 中有一个方法

    @PostMapping("/process")
    suspend fun process(
        @RequestParam("id") id: String,
        @RequestParam("names") names: List<String>,
        @RequestParam("repositoryUri") repositoryUri: String
    ) = coroutineScope {
    ...
    }

I want to send post query from front-end desktop application and I try我想从前端桌面应用程序发送帖子查询,我尝试

        val post = HttpPost(uri)
        val builder: MultipartEntityBuilder = MultipartEntityBuilder.create()

        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
        builder.addTextBody("id", id, ContentType.DEFAULT_BINARY) // id is String, that is Ok
        builder.addTextBody("names", names, ContentType.DEFAULT_BINARY) // names is List<String>, error
        builder.addTextBody("repositoryUri", repositoryUri, ContentType.DEFAULT_BINARY) // Ok

        val entity: HttpEntity = builder.build()
        post.entity = entity
        httpclient.execute(post)

But the second param in the controller method ( names ) is not a string.但是 controller 方法( names )中的第二个参数不是字符串。 The builder has only methods addTextBody and addBinaryBody (but it doesn't seem to fit)构建器只有方法 addTextBody 和 addBinaryBody (但它似乎不适合)

How can I do it?我该怎么做?

PS I use apache PS我用的是apache

You'll need a custom format for sending a stringlist as a http form param.您需要一个自定义格式来将字符串列表作为 http 表单参数发送。

Convert the list eg to a comma separated string, you'll have to reconvert the string to a list on the server side.将列表转换为例如逗号分隔的字符串,您必须将字符串重新转换为服务器端的列表。

Or us json:或者我们 json:

ObjectMapper mapper = new ObjectMapper();
TextBody("names", mapper.writeValueAsString(names), ... )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM