美文网首页
ssm项目中request获取请求json格式的数据

ssm项目中request获取请求json格式的数据

作者: haiyong6 | 来源:发表于2019-11-05 18:55 被阅读0次

    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)的方式就能拿到参数。

    相关文章

      网友评论

          本文标题:ssm项目中request获取请求json格式的数据

          本文链接:https://www.haomeiwen.com/subject/tyyebctx.html