SpringMVC注解@RequestParam

来源:互联网 发布:云来网络 编辑:程序博客网 时间:2024/06/06 05:44

在SpringMVC后台控制层获取参数的方式主要有两种,一种是request.getParameter("name"),另外一种是用注解@RequestParam直接获取。

一、基本使用,获取提交的参数 

后端代码:

<strong><span style="color:#ff0000;">@RequestMapping("testRequestParam")      public String filesUpload(@RequestParam String inputStr, HttpServletRequest request) {  System.out.println(inputStr);int inputInt = Integer.valueOf(request.getParameter("inputInt"));System.out.println(inputInt);// ......省略return "index";    }   </span></strong>
前端代码:

<form action="/gadget/testRequestParam" method="post">   参数inputStr:<input type="text" name="inputStr">   参数intputInt:<input type="text" name="inputInt">  </form>
<span style="font-family: Helvetica, Tahoma, Arial, sans-serif; font-size: 14px; line-height: 25.2px;">前端界面:</span>

执行结果: 
test1 
123 
可以看到spring会自动根据参数名字封装进入,我们可以直接拿这个参数名来用 

二、各种异常情况处理 
1、可以对传入参数指定参数名 

@RequestParam String inputStr// 下面的对传入参数指定为aa,如果前端不传aa参数名,会报错@RequestParam(value="aa") String inputStr
错误信息: 
HTTP Status 400 - Required String parameter 'aa' is not present 
2、可以通过required=false或者true来要求@RequestParam配置的前端参数是否一定要传 

<span style="color: rgb(139, 0, 0);">// required=false表示不传的话,会给参数赋值为null,required=true就是必须要有@RequestMapping("testRequestParam")    </span><span style="color:#3333ff;"> <strong>public String filesUpload(@RequestParam(value="aa", required=true) String inputStr, HttpServletRequest request)</strong></span>
3、如果用@RequestParam注解的参数是int基本类型,但是required=false,这时如果不传参数值会报错,因为不传值,会赋值为null给int,这个不可以
<span style="color:#8b0000;">@RequestMapping("testRequestParam")      public String filesUpload(@RequestParam(value="aa", required=true) String inputStr,     </span><strong><span style="color:#3366ff;">@RequestParam(value="inputInt", required=false) int inputInt</span></strong><span style="color:#8b0000;">    ,HttpServletRequest request) {  // ......省略return "index";    }</span>
解决方法: 
    “Consider declaring it as object wrapper for the corresponding primitive type.”建议使用包装类型代替基本类型,如使用“Integer”代替“int”
<!--以上文章转载自ITEYE 825635381 无量 -->


0 0