今天在Spring的Controller层中写了一个方法,如下:
@RequestMapping("/time/total")
public Map<?, ?> timeTotal(@RequestParam(value = "type", required = false) int type) {
if(type == 0){
// doSomethingA
} else if(type == 1){
// doSomethingB
}
}
type作为一个类型判断,取值范围是 0和1,而且type是非必传字段。取值0或1时,分别返回不同类型查询结果,如果不传值,则将两种类型结果都返回。
使用中发现,前端页面不给 type 赋值时,type每次都有默认返回值 0,这就有些尴尬了。经查,int 基础数据类型数据默认值是 0,思考之后,将入参类型改为包装类,如下:
@RequestMapping("/time/total")
public Map<?, ?> timeTotal(@RequestParam(value = "type", required = false) Integer type) {
if(null != type && type == 0){
// doSomethingA
} else if(null != type && type == 1){
// doSomethingB
} else if(null == type){
// doSomethingA
// doSomethingB
}
}
完。