Spring MVC 的@RequestParam注解和request.getParameter("XXX")

在SpringMVC后台控制层获取参数的方式主要有两种,一种是request.getParameter("name"),另外一种是用注解@RequestParam直接获取。这里主要讲这个注解 
一、基本使用,获取提交的参数 
后端代码:
 

  1. @RequestMapping("testRequestParam")    
  2.    public String filesUpload(@RequestParam String inputStr, HttpServletRequest request) {    
  3.     System.out.println(inputStr);  
  4.       
  5.     int inputInt = Integer.valueOf(request.getParameter("inputInt"));  
  6.     System.out.println(inputInt);  
  7.       
  8.     // ......省略  
  9.     return "index";  
  10.    }     

前端代码: 

  1. <form action="/gadget/testRequestParam" method="post">    
  2.      参数inputStr:<input type="text" name="inputStr">    
  3.      参数intputInt:<input type="text" name="inputInt">    
  4. </form>  

前端界面: 
id="iframe_0.1233806861564517" src="data:text/html;charset=utf8,%3Cimg%20id=%22img%22%20src=%22http://dl2.iteye.com/upload/attachment/0107/0827/1b03fa2c-3a6a-37f9-9c25-28131a70c8be.png?_=5342068%22%20style=%22border:none;max-width:1098px%22%3E%3Cscript%3Ewindow.onload%20=%20function%20()%20%7Bvar%20img%20=%20document.getElementById('img');%20window.parent.postMessage(%7BiframeId:'iframe_0.1233806861564517',width:img.width,height:img.height%7D,%20'http://www.cnblogs.com');%7D%3C/script%3E" frameborder="0" scrolling="no" style="border-style: none; width: 302px; height: 119px;"> 

执行结果: 
test1 
123 

可以看到spring会自动根据参数名字封装进入,我们可以直接拿这个参数名来用 
二、各种异常情况处理 
1、可以对传入参数指定参数名
 

  1. @RequestParam String inputStr  
  2. // 下面的对传入参数指定为aa,如果前端不传aa参数名,会报错  
  3. @RequestParam(value="aa") String inputStr  

错误信息: 
HTTP Status 400 - Required String parameter 'aa' is not present 
2、可以通过required=false或者true来要求@RequestParam配置的前端参数是否一定要传
 

  1. // required=false表示不传的话,会给参数赋值为null,required=true就是必须要有  
  2. @RequestMapping("testRequestParam")    
  3.     public String filesUpload(@RequestParam(value="aa", required=true) String inputStr, HttpServletRequest request)  

3、如果用@RequestMapping注解的参数是int基本类型,但是required=false,这时如果不传参数值会报错,因为不传值,会赋值为null给int,这个不可以 

  1. @RequestMapping("testRequestParam")    
  2.    public String filesUpload(@RequestParam(value="aa", required=true) String inputStr,   
  3.         @RequestParam(value="inputInt", required=false) int inputInt  
  4.         ,HttpServletRequest request) {    
  5.       
  6.     // ......省略  
  7.     return "index";  
  8.    }  

解决方法: 
    “Consider declaring it as object wrapper for the corresponding primitive type.”建议使用包装类型代替基本类型,如使用“Integer”代替“int”

转自:http://www.cnblogs.com/zhangshitong/p/5342068.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值