springmvc异常之.....Consider declaring it as object wrapper for the corresponding primitive type....

编程知识 更新时间:2023-05-02 05:34:51

一、错误描述

使用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

本文发布于:2023-04-26 07:21:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/64546b6d4ded3ee7bf510e0831a53291.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:异常   declaring   springmvc   object   type

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 104690文章数
  • 26218阅读数
  • 0评论数