問題描述:使用 request.getParameterMap 無法獲取到 swagger 調用接口傳遞的參數,接口接收參數使用了 @RequestBody 接收的參數。
解決方案:
1.使用 @RequestParam("id") 接收參數,但是這個多用於只有 一到二個參數傳遞,不適用多個參數傳遞。
2.接口接收參數不使用 @RequestBody 注解接收。
問題出現的原因就是因為使用了 @RequestBody 。因為 @RequestBody 把接口參數轉化成了 String 字符串,所以無法獲取到參數。如果方法中傳遞的是 查詢 db 類的對象的話 是可以獲取到對象的。
獲取請求參數demo:
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); //獲取 請求參數的 鍵值對 Map<String, String[]> requestParams= request.getParameterMap(); /** * 請求參數Map轉換驗證Map * * @param requestParams * 請求參數Map * @param charset * 是否要轉utf8編碼 * @return * @throws UnsupportedEncodingException */ public static Map<String, String> toVerifyMap(Map<String, String[]> requestParams, boolean charset) { Map<String, String> params = new HashMap<>(); for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) { String name = (String) iter.next(); String[] values = requestParams.get(name); String valueStr = ""; for (int i = 0; i < values.length; i++) { valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ","; } // 亂碼解決,這段代碼在出現亂碼時使用。如果mysign和sign不相等也可以使用這段代碼轉化 if (charset) valueStr = getContentString(valueStr, INPUT_CHARSET); params.put(name, valueStr); } return params; }