如何把前端传过来的Json对象解析出来?在java web应用中,我们如何获取post请求body中的内容?
通常利用request获取参数可以直接通过req.getParameter(name)的方式获取url上面或者ajax data提交上来的参数。但是body是没有名字的,无法通过参数名字这种方式获取。这时候需要用到io流的方式来获取body中的内容。
packagecom.example.controller;importjava.io.BufferedReader;importjava.io.InputStreamReader;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importorg.springframework.boot.autoconfigure.EnableAutoConfiguration;importorg.springframework.web.bind.annotation.PathVariable;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RestController;importcom.alibaba.fastjson.JSONObject;
@RestController
@EnableAutoConfigurationpublic classExample {
@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= newStringBuilder();
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();
}returnparam;
}
@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