一、错误描述
使用springmvc处理请求参数时,出现异常
500
java.lang.IllegalStateException: Optional int parameter 'userId' is present but cannot be translated into a null value due to being declared as a primitive type. Consider declaring it as object wrapper for the corresponding primitive type.
示例代码:
@RequestMapping(value="/findBy")
public String findBy(@RequestParam(value="userId")int id,
@RequestParam(value="userName")String name){
System.out.println("--- UserController findBy...");
log.info("自定义日志信息:id="+id+",name = "+name);
return "userAdd";
}
访问服务器的地址:
http://localhost/xyjj/user/findBy?id=9&name=钱多多
二、错误分析
1、@RequestParam注解的使用
我们先了解一下@RequestParam注解的使用
@RequestParam注解的使用:
value="指定请求参数名"
required="true(默认值)|false" 指定该注解对应的请求参数值是否是可以为null
true表示是必须的,不能为null, 默认值是true
false表示非必须,可以为null
defaultValue="指定请求参数的默认值"
如果请求参数传入值,请求参数值就是请求传入的内容
如果方法参数没有传入值,请求参数值就是默认值
注意:如果@RequestParam只是为了命名一个请求参数名,
完整语法:@RequestParam(value="userId")int userId... ,
可以简化成: @ReuqestParam("userId")int userId...
2、错误原因分析
错误原因分析:
1)对于简单类型的参数,例如java的8中基本数据类型,或者String类型,如果方法参数没有添加@RequestParam注解,springmvc默认会将方法参数名当成请求参数名进行映射。
2)配置了@RequestParam(value="userId")int id, 该方法参数的id就不再对应请求参数名,这时请求参数名应该是userId,
由于我们的访问路径是http://localhost/xyjj/user/findBy?id=9&name=钱多多
所以,springmvc无法正确的映射请求参数,因此控制器方法对应的请求参数值就是空值null,而根据@RequestParam注解的使用方法,是不允许这些请求参数为null值的,所以,出现以上异常。
此文希望可以帮助到大家。如有错误,请指教。
如果大家还有其他的情况或者好的解决方法,也望指教,感谢阅读。
更多推荐
springmvc异常之.....Consider declaring it as object wrapper for the corresponding p
发布评论