如何把前端傳過來的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參數就失效了(親測返回"")java
參考:web
一、http://blog.techbeta.me/2015/12/java-http-json/ajax
二、https://blog.csdn.net/qq_27292113/article/details/76837603spring