zoukankan      html  css  js  c++  java
  • SpringMVC @RequestParam

    案例来说明

    @RequestMapping("user/add")
    public String add(@RequestParam("name") String name,
                @RequestParam("age") int age){
            System.out.println(name+","+age);
        return "hello";
    }

    测试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,表示该属性不是必须的

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

    输出结果:null,18

     测试3

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

     同样出现上面的异常

    那么根据上面的方法设置

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

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

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

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

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

    结果正确输出:caoyc,null

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

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

    结果输出:caoyc,0

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

    还有相识的注解

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

    本文转自:http://www.cnblogs.com/caoyc/p/5635427.html

  • 相关阅读:
    (五)CSS和JavaScript基础
    (四)标签框架
    (三)表单与servlet的初步结合
    (三)文档结构(上)
    (二十一)持有对象以及泛型基础(1)
    (二十)内部类详解(转)
    (十九)接口类型的简介
    nginx配置文件
    nginx负载均衡
    debian iptables持久化
  • 原文地址:https://www.cnblogs.com/jasonZh/p/8761034.html
Copyright © 2011-2022 走看看