本文共 1567 字,大约阅读时间需要 5 分钟。
在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>
前端界面: 执行结果: test1
123
可以看到spring会自动根据参数名字封装进入,我们可以直接拿这个参数名来用 二、各种异常情况处理 1、可以对传入参数指定参数名 - @RequestParam String inputStr
-
- @RequestParam(value="aa") String inputStr
错误信息: HTTP Status 400 - Required String parameter 'aa' is not present 2、可以通过required=false或者true来要求@RequestParam配置的前端参数是否一定要传 -
- @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://dojqi.baihongyu.com/