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

后端 未结 5 1185
感动是毒
感动是毒 2020-11-27 02:53

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 sen

相关标签:
5条回答
  • 2020-11-27 03:31

    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)

    0 讨论(0)
  • 2020-11-27 03:37

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

    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
    
    0 讨论(0)
  • 2020-11-27 03:40
    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)

    0 讨论(0)
  • 2020-11-27 03:46

    You should do something like this:

    Call:

    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";
    }
    
    0 讨论(0)
  • 2020-11-27 03:56

    At first, put this in your code (Add @PathVariable) :

    @GetMapping(path="/test/{firstNameIds}",produces = {"application/json"})
    public String test(@PathVariable List<String> firstNameIds)
    {
         return "Dummy"; 
    }
    

    You'd pass in: http://localhost:8080/public/test/Agent,xxx,yyyy

    0 讨论(0)
提交回复
热议问题