简体   繁体   English

Spring Boot-如何在Spring RestController中的映射中获取所有请求参数?

[英]Spring Boot - How to get all request params in a map in Spring RestController?

Sample URL: 范例网址:

../get/1?attr1=1&attr2=2&attr3=3

I do not know the names of attr1, att2, and attr3. 我不知道attr1,att2和attr3的名称。

When I ran this code, I get the size of 'allRequestParams' equals to 1 当我运行此代码时,我得到的“ allRequestParams”的大小等于1

@RequestMapping(value = "/get/", method = RequestMethod.GET)
public String search(
@RequestParam Map<String,Integer> allRequestParams) {
   System.out.println(allRequestParams.size());
   return "";
}

Is it problem with Spring or I wrote a wrong code. 是Spring的问题还是我写错了代码。 Thank you! 谢谢!

You can define a POJO which contains a map.. Something like below: 您可以定义一个包含地图的POJO。如下所示:

@RequestMapping(value = "/get/{searchId}", method = RequestMethod.POST)
public String search(
@PathVariable("searchId") Long searchId,
@RequestParam SearchRequest searchRequest) {
 System.out.println(searchRequest.getParams.size());
 return "";
}

public class SearchRequest {   
private Map<String, String> params;
}

Request Object: 请求对象:

"params":{
     "birthDate": "25.01.2011",
    "lang":"en"       
 }

For your specific example aren't you missing a @PathVariable to access Path variable with value "1" in your example URL? 对于您的特定示例,您是否未缺少@PathVariable来访问示例URL中值为“ 1”的Path变量?

@RequestMapping(value = "/get/{searchId}", method = RequestMethod.GET)
public String search(
@PathVariable("searchId") Long searchId,
@RequestParam Map<String,String> allRequestParams) {
   System.out.println(allRequestParams.size());
   return "";
}

Also, are you importing java.util.Map? 另外,您要导入java.util.Map吗?

If you are passing the request attributes in the form of query parameters then you can directly get it using HttpServletRequest. 如果您以查询参数的形式传递请求属性,则可以使用HttpServletRequest直接获取它。 Pass in as the parameter to your method and use it like httpServletRequest.getParameterMap(). 将参数作为参数传递给您的方法,并像httpServletRequest.getParameterMap()一样使用它。 This will return an immutable java.util.Map of request parameters. 这将返回一个不变的请求参数java.util.Map。 Each entry of the map will have the key of type String and value of type String[]. 映射的每个条目将具有String类型的键和String []类型的值。 So if you have only one value you can directly access as entry.getValue()[0] would give you the first value. 因此,如果只有一个值,则可以直接作为entry.getValue()[0]进行访问。 Code looks something like this to access the values. 代码看起来像这样来访问值。

@RequestMapping(value = "/get/", method = RequestMethod.GET) 
public String search(HttpServletRequest httpServletRequest) {
   Map<String, String[]> requestParameterMap = httpServletRequest.getParameterMap();
   for(String key : requestParameterMap.keySet()){
        System.out.println("Key : "+ key +", Value: "+ requestParameterMap.get(key)[0]);
   }
   return "";
}

Hope this helps !! 希望这可以帮助 !!

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

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