(1)假设请求地址是如下这种,有多个同名参数:

http://localhost:8080/hello?name=hangge&name=google

(2)我们可以定义一个数组类型的参数来接收:

package com.example.demo;

import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.bind.annotation.RestController;

import org.springframework.web.bind.annotation.GetMapping;

@RestController

public class HelloController {

@GetMapping("/hello")

public String hello(@RequestParam("name") String[] names) {

String result = "";

for(String name:names){

result += name + "
";

}

return result;

}

}

附:使用对象来接收参数

1,基本用法

(1)如果一个 get 请求的参数太多,我们构造一个对象来简化参数的接收方式:

package com.example.demo;

import org.springframework.web.bind.annotation.RestController;

import org.springframework.web.bind.annotation.GetMapping;

@RestController

public class HelloController {

@GetMapping("/hello")

public String hello(User user) {

return "name:" + user.getName() + "
age:" + user.getAge();

}

}

(2)User 类的定义如下,到时可以直接将多个参数通过 getter、setter 方法注入到对象中去:

package com.example.demo;

public class User {

private String name;

private Integer age;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public Integer getAge() {

return age;

}

public void setAge(Integer age) {

this.age = age;

}

}

(3)下面是一个简单的测试样例:

(4)如果传递的参数有前缀,且前缀与接收实体类的名称相同,那么参数也是可以正常传递的:

2,指定参数前缀

(1)如果传递的参数有前缀,且前缀与接收实体类的名称不同相,那么参数无法正常传递:

(2)我们可以结合 @InitBinder解决这个问题,通过参数预处理来指定使用的前缀为 u.

除了在 Controller 里单独定义预处理方法外,我们还可以通过 @ControllerAdvice结合 @InitBinder 来定义全局的参数预处理方法,方便各个 Controller 使用。具体做法参考我之前的文章:

package com.example.demo;

import org.springframework.web.bind.WebDataBinder;

import org.springframework.web.bind.annotation.*;

@RestController

public class HelloController {

@GetMapping("/hello")

public String hello(@ModelAttribute("u") User user) {

return "name:" + user.getName() + "
age:" + user.getAge();

}

@InitBinder("u")

private void initBinder(WebDataBinder binder) {

binder.setFieldDefaultPrefix("u.");

}

}

(3)重启程序可以看到参数以及成功接收了:

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐