如何在Spring Rest模板中将数组作为PathVariable传递?

时间:2018-07-11 10:14:34

标签: arrays spring resttemplate url-parameters path-variables

我想将数组作为URL中的路径参数传递。

我的代码如下:

控制器:

@RequestMapping(value = "/getAllProcessInstancesByLocation/[{location_id}]" , method = RequestMethod.GET)
     public String getAllProcessInstances(@PathVariable("location_id") String[] location_id) {
         try {
        return processService.getAllProcessInstancesByLocation(location_id);
         }catch(Exception e) {
             return "error=>"+e.getMessage();
         }

     }

当我尝试通过浏览器进行测试时,出现以下错误:

  

http://localhost:8088/super-admin/getAllProcessInstancesByLocation/[%7B8,9%7D]

     

Whitelabel错误页面   此应用程序没有针对/ error的显式映射,因此您将其视为后备。   IST 2018年7月11日星期三12:54:55   发生意外错误(类型=内部服务器错误,状态= 500)。   无法获取HttpServletRequest URI:索引67:http://localhost:8088/super-admin/getAllProcessInstancesByLocation/[%7B8,9%7D]

路径中的非法字符

如何在url中传递数组?我想通过以下内容:

http://localhost:8088/super-admin/getAllProcessInstancesByLocation/[7,9,11]

1 个答案:

答案 0 :(得分:0)

应该是

@RequestMapping(value = "/getAllProcessInstancesByLocation/{location_id}" ...

不是

@RequestMapping(value = "/getAllProcessInstancesByLocation/[{location_id}]" ...

例如,以下控制器在调用["a","b","c","1","2","3"]时将返回GET http://localhost:8080/getAllProcessInstancesByLocation/a,b,c,1,2,3

@Controller
public class MyController {
    @RequestMapping("/getAllProcessInstancesByLocation/{locationId}")
    @ResponseBody
    public String[] getAllProcessInstances(@PathVariable String[] locationId){
        return locationId;
    }
}