首页 > 解决方案 > 在服务中获取 PathVariables、RequestParams、RequestBody

问题描述

我想从 à spring 服务组件中的 httpRequest 获取所有参数(不需要标头)

我正在使用 Spring Boot,看看这个例子:

private final MyService myService;

@RequestMapping(value = "/processform/{process_id}", method = RequestMethod.POST)
    public @ResponseBody
    LinkedHashMap<String, String> runForm( String process_id,
                                               @RequestParam String className,
                                               @RequestBody(required = false) IupicsFormVO vo) {
        return myService.run(process_id, className, vo);
    }

这个控制器生成这个 curl(没有标题):

curl -X POST \
  'http://localhost:8087/processform/119?className=com.stackOverflow.question.ClassName.java' \
  -d '{  
"name" : "Name",
"age" : "Age"
}'

现在我需要的是从这个 URL 获取所有参数(可能是注入HttpServletRequest

预期的结果是:

{  
   "process_id":"119",
   "className":"com.stackOverflow.question.ClassName.java",
   "body":{  
      "name":"Name",
      "age":"Age"
   }
}

我找到了这个例子,

String finalPath = apm.extractPathWithinPattern(bestMatchPattern, path

但是当我使用它时,我总是得到空的 finalPath 感谢您的时间

标签: javaspringspring-bootjava-8httprequest

解决方案


您的路径应该有路径变量占位符。/processform/{process_id}. 您还需要指定request parameter

@RequestMapping(value = "/processform/{process_id}", method = RequestMethod.POST)
    public @ResponseBody
    LinkedHashMap<String, String> runForm(HttpServletRequest request, @PathVariable("process_id") String process_id, @RequestParam("name") String lassName,@RequestParam("age") String age,
                                               @RequestBody(required = false) IupicsFormVO vo) {
        return myService.run(process_id, className, vo);
    }

有关路径变量和请求参数的更多详细信息,您可以查看本教程。

编辑:如果你想从请求中获取这些属性,那么第一个参数将HttpServletRequest request在你的控制器方法中。将参数传递request给您的服务,您可以在那里使用request.getParameter("paramName")request.getAttribute("attributeName")访问这些值。


推荐阅读