当前位置:首页 > IT技术 > 移动平台 > 正文

Servlet POST 请求 ,获取 前端 “application/json”类 的数据
2021-12-01 23:03:53

众所周知 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;
    }
View Code

 

 

 

 

配合 阿里巴巴 的 fastJSON

 

等写好了 写个  “vue + servlet”  的 “注意点” 笔记吧。

本文摘自 :https://www.cnblogs.com/