HTTP Status 500 - Could not write content

版权声明:本文为博主原创文章,转载请注明原文链接哦,forethought.top! https://blog.csdn.net/qq_36922927/article/details/85111328

后台查询数据向前端返回数据时报错:
HTTP Status 500 - Could not write content****

1,原因:

执行对应的sql发现有一个字段查出来时是null的,
而封装到某个对象中时,并未给属性是否为null,检测,如果为null就赋予一个符合该属性类型的值,即可。


   if (!Objects.isNull(row[8])) {
            tempOrderId = (Integer) row[8];
        } else {
            tempOrderId = 0;
        }

2,疑问

比较奇特的是:debug看见数据已经被封装到对象中,但是在controller层转为json就抛异常了
如下图:
图片.png
详细异常信息:

HTTP Status 500 - Could not write content: (was java.lang.NullPointerException) (through reference chain: com.werun.template.common.utils.BaseObjectResult[“data”]->com.werun.template.api.model.OrderModifyNoticeDetailResultBean[“tempOrderId”]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.NullPointerException) (through reference chain: com.werun.template.common.utils.BaseObjectResult[“data”]->com.werun.template.api.model.OrderModifyNoticeDetailResultBean[“tempOrderId”])

为什么会这样呢?按照报错信息翻译是空指针异常,进一步databind异常了,

3,这条数据可是有10多个字段,难道每个字段去加if和else?

再回到代码中:
发现数据类型都是使用的封装类型Integer,但是没有改变setter、getter

public int getTempOrderId() {
        return tempOrderId;
    }
    public void setTempOrderId(int tempOrderId) {
        this.tempOrderId = tempOrderId;
    }

java类转为json类是通过getter方法来生成json的具体属性的,getXXX 就会生成一个XXX的json串的属性

4,真实原因:

这里由于 属性 tempOrderId 是Integer类型,并且为null,调用get时会自动拆箱为int,但是null给拆成为int是啥效果呢?
可以写代码试试:

   @Test
    public void testInteger(){
        Integer a=null;
        int b=a;
}

控制台输出:

java.lang.NullPointerException
at com.werun.template.common.TestUtil.testInteger(TestUtil.java:797)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method),

5,验证

为了验证猜想:将getter的返回参数有int改为Integer(只更改getter返回值类型)

public Integer getTempOrderId() {
        return tempOrderId;
    }
    public void setTempOrderId(int tempOrderId) {
        this.tempOrderId = tempOrderId;
    }

测试:
{
“message”: “获取成功”,
“data”: {
“noticeId”: 164,
“noticeNum”: “1545132031742”,
“noticeTime”: 1545132031740,
“noticeTypeCode”: “14010”,
“noticeTypeName”: “订单中止审核”,
“modifierId”: 272,
“modifierName”: “张三”,
“orderId”: 13,
“tempOrderId”: null,//这个字段在作怪
“orderNum”: “K1,0,501”,
“clientId”: 11,
“clientName”: “,,,,,测试”,
“orderStatusCode”: “,,,”,
“orderStatusName”: “,,,”,
“modifyContent”: “,,,”,
“remarks”: “设计主管处 同意终止订单1363”,
“auditResultCode”: “1300”,
“auditResultName”: “接单”
},
“success”: true
}

至此问题解决!
包装类型->基本类型可能有问题
基本类型->包装类型,没问题

6总结:

数据库查询出的结果尽量使用包装类型,避免null造成的影响
运算的地方使用基本类型,减少对象的创建

猜你喜欢

转载自blog.csdn.net/qq_36922927/article/details/85111328