springmvc学习笔记(5)——RequestParam

来源:互联网 发布:如何设置bios网络唤醒 编辑:程序博客网 时间:2024/06/03 17:47

RequestParam也是一个非常常用的注解,它用来获取参数值,相当于request.getParameter("key")的作用。直接上代码:

/** *  * @RequestParam 映射请求参数  * required 是否是必传参数,默认为true * defaultValue 参数默认值 */@RequestMapping("/testRequestParam")public String testRequestParam(@RequestParam("name")String name,@RequestParam(value="age",required=false,defaultValue="0")Integer age){System.out.println("name="+name+" and age="+age);return "hello";}

从浏览器访问
http://localhost:8083/springmvc01/testRequestParam?name=hehe&age=1


代码解析:

RequestParam使用大家一看代码就能明白了。required默认值为true,那么访问的时候,就必须传name这个参数,age的required为false,可传可不传。defaultValue是参数的默认值,如果没有传age这个参数,那么age就等于0.

这里需要注意的一点是,如果你没有给age参数设置defaultValue,那么访问时没有传age这个参数,age的值为null,这没问题。如果你是这样写的:

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

当你不传参数age访问时,将会报错,因为int是基本数据类型,不能为null。

0 0
原创粉丝点击