axios がサーブレットを使用してリクエストをバックエンドに送信して受信すると、NullPointerException が発生します。

axios で追加リクエストを送信する練習をしているときに、null ポインター例外が発生しました。

insertOrUpdateGood:function(){
    
    
    let that = this;
    axios({
    
    
           method: "post",
           url: "goods/insertOrUpdateGood",
           data: this.form
     }).then(function (response) {
    
    
            console.log(response.message);
            that.dialogFormVisible = false;
            that.loadData();
        },
        (error) => {
    
    
             console.log("错误", error);
        }
    );
}

F12 を開くと、リクエスト ヘッダーを自分で設定しない場合、デフォルトのリクエスト ヘッダーは次のようになります:
ここに画像の説明を挿入
バックエンドはサーブレットを使用するため、フレームワークのようにアノテーションを追加することで指定されたパラメーターを受け取ることができません。このとき、 Map <String, String[]>parameterMap = req.getParameterMap(); データを受信すると、受信したデータはすべて null であることがわかり、当然 null ポインタ例外が発生します。

解決策: ストリーム経由でデータを読み取る

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        StringBuffer stringBuffer = new StringBuffer("");
        BufferedReader reader = req.getReader();
        String str = null;
        while ((str = reader.readLine()) != null) {
    
    
            stringBuffer.append(str);
        }
        str = stringBuffer.toString();
        Goods goods = JSONObject.parseObject(str, Goods.class);
        Message msg = null;
        Integer i = null;

        if(goods.getId() == null){
    
    
            i = goodDao.addGoodInfo(goods);
            if (i > 0) {
    
    
                msg = new Message("新增成功", true, null);
                resp.getWriter().write(JSON.toJSONString(msg));
            } else {
    
    
                msg = new Message("新增失败", false, null);
                resp.getWriter().write(JSON.toJSONString(msg));
            }
        }
        else {
    
    
            i = goodDao.updateGoodById(goods);
            if (i > 0) {
    
    
                msg = new Message("修改成功", true, null);
                resp.getWriter().write(JSON.toJSONString(msg));
            } else {
    
    
                msg = new Message("修改失败", false, null);
                resp.getWriter().write(JSON.toJSONString(msg));
            }
        }
    }

おすすめ

転載: blog.csdn.net/weixin_44834205/article/details/125234761