zoukankan      html  css  js  c++  java
  • Spring MVC @RequestParam(5)

    案例来说明

    复制代码
    1 @RequestMapping("user/add")
    2 public String add(@RequestParam("name") String name,
    3             @RequestParam("age") int age){
    4         System.out.println(name+","+age);
    5     return "hello";
    6 }
    复制代码

    测试1

    当我们请求路径为:http://localhost:8080/springmvc-1/user/add?name=caoyc&age=18

    输出结果:caoyc,18

    测试2

    当我请求路径为:http://localhost:8080/springmvc-1/user/add?age=18

    输出结果:有异常出现。意思是说必须要有该参数

    解决方案:在@RequestParam标签中添加一个required=false,表示该属性不是必须的

    1 @RequestParam(value="name",required=false)

    输出结果:null,18

     测试3

     当我请求路径为:http://localhost:8080/springmvc-1/user/add?name=caoyc

     同样出现上面的异常

    那么根据上面的方法设置

    1 @RequestParam(value="age",required=false) int age

    结果再运行。还是抛出异常

    这里也说到很明白,大概意思是说不能讲一个null的空值赋给age。应该使用包装类型

    那么我们将代码改成这样:

    1 @RequestParam(value="age",required=false) Integer age

    结果正确输出:caoyc,null

    这里还有另外一种改法:给参数指定一个默认值

    1 @RequestParam(value="age",required=false,defaultValue="0") int age

    结果输出:caoyc,0

    【总结】对应@RequestParam基本类型的参数我们最好都使用包装类型

    还有相识的注解

    @RequestHeader。使用方式和@RequestParam一样。这里就不做多的讲解了。

  • 相关阅读:
    CSS-DAY03
    Java语言支持的8种基本数据类型
    Linux目录结构
    面向对象的四个基本特征
    使用AVADA头部有搜索icon怎么去掉?
    在ubuntu 上使用apt-get安装 任意版本
    ubuntu 14.04 nginx 1.12.2 配置https遇见的坑
    java Process执行linux命令
    node.js 接收上传的文件
    node.js 进行http get 向服务端请求
  • 原文地址:https://www.cnblogs.com/weiqingfeng/p/9498166.html
Copyright © 2011-2022 走看看