我试图使用HttpServletRequest的.getParameterMap()访问POST请求正文中的内容,以便填充POJO。但是,尽管有证据表明主体不是空的,但它仍返回一个空的地图:
控制器:
@PostMapping(path = "/categories/{effectiveCategory}", produces = MediaType.APPLICATION_JSON_VALUE)
public List<Announcement> getEffectiveCategoryAnnouncements(@PathVariable("effectiveCategory") String effectiveCategory, HttpServletRequest request) throws Exception{
AnnouncementFilter filter = new AnnouncementFilter();
logger.debug("request body: " + request.getReader().lines().collect(Collectors.joining(System.lineSeparator())));
logger.debug("request parameter map size: " + request.getParameterMap().size());
logger.debug("Content-Type header value: " + request.getHeader("Content-Type"));
logger.debug("request URL: " + request.getRequestURL());
logger.debug("request query string: " + request.getQueryString());
logger.debug("request 'province' attribute: " + request.getAttribute("province"));
logger.debug("request 'province' parameter: " + request.getParameter("province"));
logger.debug("request content length: " + request.getContentLength());
for(Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()){
switch(entry.getKey()){
case "province":
filter.setProvince(entry.getValue()[0]);
break;
case "minPrice":
filter.setMinPrice(Double.parseDouble(entry.getValue()[0]));
break;
case "maxPrice":
filter.setMaxPrice(Double.parseDouble(entry.getValue()[0]));
break;
case "announcementType":
filter.setAnnouncementType(entry.getValue()[0]);
break;
case "userType":
filter.setUserType(entry.getValue()[0]);
break;
case "orderBy":
filter.setOrderBy(entry.getValue()[0]);
break;
default:
break;
}
}
return categoryHandler.getEffectiveCategoryAnnouncements(effectiveCategory, filter);
}
请求如下:
method: POST
uri: http://localhost:8080/categories/computing
headers:
Content-Type: application-json
body: {"province": "Azuay"}
这是上述控制器方法中所有“ logger.debug()”调用的输出:
[DEBUG] 2018-08-12 09:36:06.139 [http-nio-8080-exec-1]
CategoryController - request body: {"province": "Azuay"}
[DEBUG] 2018-08-12 09:36:06.140 [http-nio-8080-exec-1]
CategoryController - request parameter map size: 0
[DEBUG] 2018-08-12 09:06:42.224 [http-nio-8080-exec-2]
CategoryController - Content-Type header value: application/json
[DEBUG] 2018-08-12 09:06:42.225 [http-nio-8080-exec-2]
CategoryController - request URL: http://localhost:8080/categories/computing
[DEBUG] 2018-08-12 09:06:42.225 [http-nio-8080-exec-2]
CategoryController - request query string: null
[DEBUG] 2018-08-12 09:06:42.225 [http-nio-8080-exec-2]
CategoryController - request 'province' attribute: null
[DEBUG] 2018-08-12 09:06:42.225 [http-nio-8080-exec-2]
CategoryController - request 'province' parameter: null
[DEBUG] 2018-08-12 09:06:42.225 [http-nio-8080-exec-2]
CategoryController - request content length: 24