当前位置:   article > 正文

Spring Boot项目误将Integer类型写成int来进行传参

Spring Boot项目误将Integer类型写成int来进行传参

在处理项目中Idea中无报错

问题:

localhost:8080/param/m2在浏览器中输入:localhost:8080/param/m2

产生报错:

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Tue Feb 27 20:55:33 GMT+08:00 2024

There was an unexpected error (type=Internal Server Error, status=500).

Optional int parameter 'id' 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.

原因为:Spring Boot项目误将Integer类型写成int来进行传参

该项目具体的代码为:(错误示范)

  1. @RestController
  2. @RequestMapping("/param")
  3. public class ParamController {
  4. @RequestMapping("/m1")
  5. public String m1(String name){
  6. return "这是你的姓名:"+name;
  7. }
  8. @RequestMapping("/m2")
  9. public String m2(String name,int id){ //错误代码,需要将int更改为Integer(包装类)
  10. return "序列号为:"+ id +"这是你的姓名:"+name;
  11. }
  12. }

解决方案:

因此,正确的代码为:(正确示范)

  1. @RestController
  2. @RequestMapping("/param")
  3. public class ParamController {
  4. @RequestMapping("/m1")
  5. public String m1(String name){
  6. return "这是你的姓名:"+name;
  7. }
  8. @RequestMapping("/m2")
  9. public String m2(String name,Integer id){
  10. return "序列号为:"+ id +"这是你的姓名:"+name;
  11. }
  12. }

重启程序,在浏览器输入:localhost:8080/param/m2?id=5&name=zhangsan

运行结果为:

在Postman中测试为:

Bug解决!!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/183961
推荐阅读
相关标签
  

闽ICP备14008679号