SpringMVC(五):@RequestMapping下使用@RequestParam绑定请求参数值
在处理方法入参使用@RequestParam可以把请求参数传递给请求方法,@RequestParam包含的属性值:
--- value :参数名称
--- required :是否必须,默认为true,表示请求参数中必须包含对应的参数,否则抛出异常。
--- defaultValue:当请求参数缺少或者有请求参数但值为空时,值采用该设置值。
示例:
1)在HelloWord.java中添加testRequestParam方法:
package com.dx.springlearn.handlers; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; @Controller @RequestMapping("class_requestmapping") public class HelloWord { private static String SUCCESS = "success"; @RequestMapping("/testRequestParam") public String testRequestParam(@RequestParam(value = "username") String username, @RequestParam(value = "address") String address, @RequestParam(value = "age", required = false, defaultValue = "0") int age) { System.out.println("testRequestParam, username: " + username + ",address: " + address + ",age: " + age); return SUCCESS; } }
2)在index.jsp中插入链接html:
<a href="class_requestmapping/testRequestParam?username=abc&address=def&age=26">testRequestParam</a> <br>
3)测试。
当请求url为:http://localhost:8080/SpringMVC_01/class_requestmapping/testRequestParam?username=abc&address=def&age=26
打印信息为:testRequestParam, username: abc,address: def,age: 26
当请求url为:http://localhost:8080/SpringMVC_01/class_requestmapping/testRequestParam?username=abc&address=def&age=
抛出异常:
Jan 04, 2018 8:02:53 PM org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver handleTypeMismatch
警告: Failed to bind request element: org.springframework.beans.TypeMismatchException:
Failed to convert value of type 'java.lang.String' to required type 'int'; nested exception is java.lang.NumberFormatException:
For input string: ""
解决方案,把age定义类型修改为Integer
当请求url为:http://localhost:8080/SpringMVC_01/class_requestmapping/testRequestParam?username=abc&address=def
打印信息为:testRequestParam, username: abc,address: def,age: 0
当请求url为:http://localhost:8080/SpringMVC_01/class_requestmapping/testRequestParam?username=abc
抛出异常:
HTTP Status 400 - Required String parameter 'address' is not present
基础才是编程人员应该深入研究的问题,比如:
1)List/Set/Map内部组成原理|区别
2)mysql索引存储结构&如何调优/b-tree特点、计算复杂度及影响复杂度的因素。。。
3)JVM运行组成与原理及调优
4)Java类加载器运行原理
5)Java中GC过程原理|使用的回收算法原理
6)Redis中hash一致性实现及与hash其他区别
7)Java多线程、线程池开发、管理Lock与Synchroined区别
8)Spring IOC/AOP 原理;加载过程的。。。
【+加关注】。