gpt4 book ai didi

java - 是否可以在 Spring Controller 中拆分请求参数?

转载 作者:行者123 更新时间:2023-11-30 06:43:42 26 4
gpt4 key购买 nike

我有这样的请求:

example.com/search?sort=myfield1,-myfield2,myfield3

我想拆分这些参数来绑定(bind)一个 List<String>在我的 Controller 或 List<SortParam> 中排序其中 SortParam是具有以下字段的类:name (字符串)和 ask ( boolean 值)。

所以最终的 Controller 看起来像这样:

@RequestMapping(value = "/search", method = RequestMethod.GET)
public ResponseEntity<MyResponse> search(@RequestParam List<String> sort) {

//...
}

@RequestMapping(value = "/search", method = RequestMethod.GET)
public ResponseEntity<MyResponse> search(@RequestParam List<SortParam> sort) {

//...
}

有什么方法可以做到吗?

更新:

标准的参数传递方式不能满足我的要求。 IE。我不能使用 sort=myfield1&sort=-myfield2&sort=myfield3 .我必须使用逗号分隔的名称。
另外,我明白我可以接受 @RequestParam String sort在我的 Controller 中,然后在 Controller 内拆分字符串,如 sort.split(",")但也没有解决上述问题。

最佳答案

这只是一个简单的类型转换任务。 Spring定义了一个SPI(Service Provider Interface)来实现类型转换逻辑。对于您的特定问题,您可以通过实现 Converter 来定义类型转换逻辑。界面。

@Component
public class StringToListConverter implements Converter<String, List<String>> {

@Override
public List<String> convert(String source) {
return Arrays.asList(source.split(","));
}
}

您还可以将您的请求参数转换为List<SortPram>根据您的逻辑(但我不确定您问题中的逻辑)。就是这个!现在 Spring 知道如何将您的请求参数绑定(bind)到列表。

@RequestMapping(value = "/search", method = RequestMethod.GET)
public ResponseEntity<MyResponse> participants(@RequestParam("sort") List<String> sort) {
// .. do your logic
}

还有很多方法可以定义您的自定义数据绑定(bind)器。检查这个

关于java - 是否可以在 Spring Controller 中拆分请求参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51840534/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com