將數組或列表傳遞給@Path變量 - Spring / Java

[英]Passing an Array or List to @Pathvariable - Spring/Java


I am doing a simple 'get' in JBoss/Spring. I want the client to pass me an array of integers in the url. How do I set that up on the server? And show should the client send the message?

我在JBoss / Spring中做了一個簡單的'get'。我希望客戶端在url中傳遞一個整數數組。如何在服務器上進行設置?並顯示客戶端應該發送消息?

This is what I have right now.

這就是我現在所擁有的。

@RequestMapping(value="/test/{firstNameIds}", method=RequestMethod.GET)
@ResponseBody
public String test(@PathVariable List<Integer> firstNameIds)
{
     //What do I do??
     return "Dummy"; 
}

On the client I would like to pass something like

在客戶端我想通過類似的東西

http://localhost:8080/public/test/[1,3,4,50]

When I did that I get an error:

當我這樣做時,我收到一個錯誤:

java.lang.IllegalStateException: Could not find @PathVariable [firstNameIds] in @RequestMapping

java.lang.IllegalStateException:在@RequestMapping中找不到@PathVariable [firstNameIds]

4 个解决方案

#1


38  

GET http://localhost:8080/public/test/1,2,3,4

@RequestMapping(value="/test/{firstNameIds}", method=RequestMethod.GET)
@ResponseBody
public String test(@PathVariable String[] firstNameIds)
{
    // firstNameIds: [1,2,3,4]
    return "Dummy"; 
}

(tested with Spring MVC 4.0.1)

(使用Spring MVC 4.0.1測試)

#2


22  

You should do something like this:

你應該做這樣的事情:

Call:

呼叫:

GET http://localhost:8080/public/test/1,2,3,4

GET http:// localhost:8080 / public / test / 1,2,3,4

Your controller:

你的控制器:

@RequestMapping(value="/test/{firstNameIds}", method=RequestMethod.GET)
@ResponseBody
public String test(@PathVariable List<Integer> firstNameIds) {
     //Example: pring your params
     for(Integer param : firstNameIds) {
        System.out.println("id: " + param);
     }
     return "Dummy";
}

#3


9  

if you want to use Square brackets - []

如果你想使用方括號 - []

DELETE http://localhost:8080/public/test/[1,2,3,4]

@RequestMapping(value="/test/[{firstNameIds}]", method=RequestMethod.DELETE)
@ResponseBody
public String test(@PathVariable String[] firstNameIds)
{
    // firstNameIds: [1,2,3,4]
    return "Dummy"; 
}

(Tested with Spring MVC 4.1.1)

(使用Spring MVC 4.1.1測試)

#4


4  

Could do @PathVariable String ids, then parse the string.

可以做@PathVariable String ids,然后解析字符串。

So something like:

所以類似於:

@RequestMapping(value="/test/{firstNameIds}", method=RequestMethod.GET)
@ResponseBody
public String test(@PathVariable String firstNameIds)
{
     String[] ids = firstNameIds.split(",");
     return "Dummy"; 
}

You'd pass in:

你會傳入:

http://localhost:8080/public/test/1,3,4,50

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2012/03/08/7207e6bddad355d2144fdea8ddc61a1c.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com