在SpringMVC后台控制层获取参数的方式主要有两种,一种是request.getParameter("name"),另外一种是用注解@RequestParam直接获取。这里主要讲这个注解
一、基本使用,获取提交的参数
后端代码:
- @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";
- }
前端代码:
- <form action="/gadget/testRequestParam" method="post">
- 参数inputStr:<input type="text" name="inputStr">
- 参数intputInt:<input type="text" name="inputInt">
- </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、可以对传入参数指定参数名
- @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配置的前端参数是否一定要传
- // required=false表示不传的话,会给参数赋值为null,required=true就是必须要有
- @RequestMapping("testRequestParam")
- public String filesUpload(@RequestParam(value="aa", required=true) String inputStr, HttpServletRequest request)
3、如果用@RequestMapping注解的参数是int基本类型,但是required=false,这时如果不传参数值会报错,因为不传值,会赋值为null给int,这个不可以
- @RequestMapping("testRequestParam")
- public String filesUpload(@RequestParam(value="aa", required=true) String inputStr,
- @RequestParam(value="inputInt", required=false) int inputInt
- ,HttpServletRequest request) {
- // ......省略
- return "index";
- }
解决方法:
“Consider declaring it as object wrapper for the corresponding primitive type.”建议使用包装类型代替基本类型,如使用“Integer”代替“int”
转自:http://www.cnblogs.com/zhangshitong/p/5342068.html