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

  • 相关阅读:
    IE设置代理后登录QQ再关闭代理仍然可以使用QQ
    ubuntu14.04下Qt开发环境搭建遇到的问题
    CButtonST使用技巧: CButtonST简介
    springboot webapi 支持跨域 CORS
    服务注册和发现 Eureka
    开发框架 springBoot
    springBoot springCloud
    springBoot 微服务
    springBoot AOP环绕增强、自定义注解、log4j2、MDC
    springBoot 热部署
  • 原文地址:https://www.cnblogs.com/jasonZh/p/8761034.html
Copyright © 2011-2022 走看看