如何把前端传过来的Json对象解析出来?在java web应用中,我们如何获取post请求body中的内容?
通常利用request获取参数可以直接通过req.getParameter(name)的方式获取url上面或者ajax data提交上来的参数。但是body是没有名字的,无法通过参数名字这种方式获取。这时候需要用到io流的方式来获取body中的内容。

package com.example.controller;

import java.io.BufferedReader;
import java.io.InputStreamReader; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import com.alibaba.fastjson.JSONObject; @RestController
@EnableAutoConfiguration
public class Example { @RequestMapping("/")
String home() {
return "Hello World!";
} // 这里我没做异常处理
@RequestMapping("/request")
String request(HttpServletRequest request, HttpServletResponse response) {
String param= null;
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); JSONObject jsonObject = JSONObject.parseObject(responseStrBuilder.toString());
param= jsonObject.toJSONString();
System.out.println(param);
} catch (Exception e) {
e.printStackTrace();
}
return param;
} @RequestMapping("/hello/{myName}")
String index(@PathVariable String myName) {
return "Hello " + myName + "!!!";
}
}

获取body参数,需要在request.getParameter()方法之前调用(如果有需要取QueryString参数的话),因为一旦调用了getParameter()方法之后,再通过IO流的方式获取body参数就失效了(亲测返回"")

参考:

1、http://blog.techbeta.me/2015/12/java-http-json/

2、https://blog.csdn.net/qq_27292113/article/details/76837603

最新文章

  1. CSS-垂直|水平居中问题的解决方法总结
  2. merge 实现
  3. 项目中用到的window.showModalDialog(来自网络)
  4. TI CC2541的中断优先级设置.
  5. hdu 5093 Battle ships
  6. java 菱形
  7. Linux 下shell显示-bash-4.1$不显示用户名路径的解决方法
  8. QQ空间自动发广告解决方法
  9. 如何煉成NET架構師
  10. scanf与printf用法详解
  11. asp.net 开发注意的几点
  12. 【linux之find及awk】
  13. 极限学习机︱R语言快速深度学习进行回归预测
  14. RPO(Relative Path Overwrite)
  15. 机器学习技法:07 Blending and Bagging
  16. Mac 使用 OpenMP/Clang
  17. JSP中EL很常用,怎样使用大于号、小于号、等于号等
  18. 微信小程序底部弹窗动画
  19. JAVA框架之Hibernate框架的学习步骤
  20. tensorflow serving 中 No module named tensorflow_serving.apis,找不到predict_pb2问题

热门文章

  1. Windows下修改oracle实例不随服务自动启动
  2. java中的抽象方法与抽象类
  3. Python使用with结构打开多个文件
  4. 【JBPM4】获取任务
  5. 处理form表单提交后返回值的处理办法【html5】
  6. ubuntu右上角红色三角警告
  7. Ubuntu 18.04安装网易云音乐(转载)
  8. IPV4网段划分
  9. ThinkPHP 多数据库自动连接设计
  10. STL容器 -- Priority_Queue