有時可能不能使用注解的方式獲取post請求中的json數據,而又需要獲取請求的參數如何處理?
所有的請求都存在於HttpServletRequest對象中,那么只需要在此對象中獲取即可:
@RequestMapping("/user") public class UserController { //獲取參數 public static JSONObject getParameters(HttpServletRequest request) throws IOException { 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()); return jsonObject; } @PostMapping("/param") public void getParam(HttpServletRequest request) throws IOException { getParameters(request); } }
關鍵部分是代碼中獲取參數的地方,從request對象中獲取流,再轉成json字符串。
不只限於controller中,其他地方也可以使用此方法獲取,前提是先得到request對象。