Servlet POST 请求 ,获取 前端 “application/json”类 的数据
众所周知 servlet 几百年前的产物 我还在用??? 非也! 我们教! 我就用!
因为要做JSP课要做项目 我不想写! 用VUE 前端 Servlet 后端, 跨域好说,只是。。。。遇到了标题这个困难,因为我太久没写过JSP了 上课也没听过一节。。。。。。
原因:request.getParameter() 获取不了application/json 格式数据,只能是 表单的那个。
下面代码是复制网上的【我已封装】 因为我心累的不想写了
原理很简单 ,获取请求头的流,然后取里面的字符即可。
直接上代码:

public class RequestUtils { public static JSONObject request2JsonString(HttpServletRequest request) throws IOException { InputStreamReader isr = new InputStreamReader(request.getInputStream(),"utf-8"); String result = ""; int respInt = isr.read(); while(respInt!=-1) { result +=(char)respInt; respInt = isr.read(); } JSONObject jsonResult = JSONObject.parseObject(result); return jsonResult; }
配合 阿里巴巴 的 fastJSON
等写好了 写个 “vue + servlet” 的 “注意点” 笔记吧。
本文来自博客园,作者:咸瑜,转载请注明原文链接:https://www.cnblogs.com/bi-hu/p/15630990.html