字符串参数默认值时null还是空字符串?
我们最怕启动项目的时候,出现空指针异常,
一般空指针异常, 是因为我们需要获取的数值变成了null造成的, 如下:
(1) request 的请求传参数时, 字段没有写默认值, 则默认为null
(2) 新增数据时, 插入了一条字段为null ,但是数据库字段要求不为null的值
postman工具中-request参数:
是否传值 | postman调用时否打钩 | 默认值 |
---|---|---|
参数不传 | postman调用时不打钩 | 默认为null |
参数传值,值为空 | postman调用时打钩 | 默认为空字符串 |
在代码中,非必填request请求参数:
参数 | 默认值 |
---|---|
String类型参数非必填, 没有给默认值 | null |
String类型参数非必填, 给默认值 defaultValue ="" | 空字符串 |
String类型参数非必填, 给默认值 defaultValue =“其他字符串” | 其他字符串 |
eg:在获取列表时,我们通常会根据关键词keyword搜索
/**
* 获取渠道列表
* @param request
* @param page
* @param size
* @param keyword
* @return
*/
@AuthSession
@RequestMapping(value = "/getChannelList", method = {
RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
public String getChannelList(HttpServletRequest request, @RequestParam("page") int page,
@RequestParam("size") int size,
@RequestParam(value = "keyword", required = false) String keyword) {
String response = cameraService.getChannelList(page, size, keyword).toJSONString();
logger.info("[获取渠道列表 response]: {}", response);
return response;
}
解:
这里的请求参数keyword值, 不是非必填值, 并且没有给出默认值, 则这里keyword 默认值是null.
如果添加默认值, 默认值 = "", 则默认值是空字符串,如下:
@RequestParam(value = "keyword", required = false, defaultValue="") String keyword