繁体   English   中英

如何使用@RequestParam在Spring MVC中请求数组类型参数时始终获取第一个参数

[英]How take always first parameter when requested array type param in spring mvc using @RequestParam

我写了这段代码。

@GetMapping("/test")
public Response search(@RequestParam String value) {
    System.out.println(value);
    return new Response(value)
}

一些身体要求

/test?value=a&value=b&value=c

值绑定到a,b,c我想始终绑定第一个参数。 a ,忽略bc

有办法使用@RequestParam吗? 还是必须使用HttpServletRequest和解析参数?

在这种情况下,您可以使用@RequestParam List<String> value代替@RequestParam String value ,并获取第一个值value.get(0)忽略其余的值

例如

http://rentacar.com/api/v1/search?make=audi&model=A8&type=6&type=11&type=12&color=RED&color=GREY

方法

public List<Vehicle> search(
@RequestParam(value="make", required=false) String make, 
@RequestParam(value="model", required=false) String model, 
@RequestParam(value="type", required=false) List<String> types, 
@RequestParam(value="color", required=false) List<String> colors)
  {
    ....
  }

好问题!

我编写了这段代码以了解其工作原理。 我将其包含在测试包中。

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
public class ControllerTest {

    @LocalServerPort
    private int port;

    private URL url;

    @Autowired
    private TestRestTemplate template;

    @Before
    public void setUp() throws Exception {
        this.url = new URL("http://localhost:" + port + "/test?value=a&value=b&value=c");
    }

    @Test
    public void getHello() throws Exception {
        ResponseEntity<String> response = template.getForEntity(url.toString(),
                String.class);
        Assert.assertEquals(HttpStatus.OK, response.getStatusCode());
        Assert.assertEquals(response.getBody(), "a");
        System.out.println("response = " + response);
    }

}

然后,我修改了您的代码以接受字符串数组,并且仅将第一个元素传递给您的Response构造函数。

注意签名和return语句中代码的更改。

@GetMapping("/test")
    public String search(@RequestParam String[] value) {
        System.out.println(value);
        return new Response(value[0]);
    }

通过测试,您现在可以对请求参数使用列表类型进行探索,并快速查看行为的变化。

暂无
暂无

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

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