NullPointerException occurs when axios sends a request backend using a servlet to receive it

When practicing axios to send an add request, a null pointer exception occurred.

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);
        }
    );
}

Open F12 and you can see that if you don’t set the request header yourself, its default request header is as follows:
insert image description here
Because the backend uses servlet, it cannot receive specified parameters by adding annotations like the framework. At this time, the backend uses it. At this time, Map <String, String[]> parameterMap = req.getParameterMap(); To receive data, you will find that the received data is all null, and a null pointer exception naturally occurs.

Solution: read data through stream

    @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));
            }
        }
    }

Guess you like

Origin blog.csdn.net/weixin_44834205/article/details/125234761