request.getParameter只能请求一些key value的数据,如果前端请求了如下截图中的post数据json格式,该如何接收呢?
image.png
通常情况下request传输这种json数据是通过InputStream流的方式,所以可以通过request.getInputStream() 获取流再转成String 字符串再转成com.alibaba.fastjson.JSONObject; 就可以拿到参数了
实例如下 controller 方法:
/**
* 获取库存数据
*/
public void getStockInfoData() {
HttpServletRequest request = getRequest();
//request.getParameter(name)
HttpServletResponse response = getResponse();
JSONObject paramsObj = AppFrameworkUtil.getRequestParamsObj(request);
Map<String, Object> paramsMap = new HashMap<String, Object>();
paramsMap.put("userId", "44A50");
paramsMap.put("ym", paramsObj.getString("ym"));//"201906"
paramsMap.put("dealerId", paramsObj.getString("dealerId"));//"44A50"
paramsMap.put("modelId", "-1");
String json = dlrHomePageService.getStockInfoData(request, paramsMap);
AppFrameworkUtil.renderJSON(response, json);
}
AppFrameworkUtil.getRequestParamsObj方法实现
/**
* 返回jsonObj参数
* @param request
* @return
*/
public static JSONObject getRequestParamsObj(HttpServletRequest request) {
JSONObject paramsObj = new JSONObject();
try {
BufferedReader streamReader = new BufferedReader( new InputStreamReader(request.getInputStream(), "UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = streamReader.readLine()) != null)
responseStrBuilder.append(inputStr);
paramsObj = JSONObject.parseObject(responseStrBuilder.toString());
} catch (Exception e) {
e.printStackTrace();
}
return paramsObj;
}
如此 通过paramsObj.getString(key)的方式就能拿到参数。
网友评论