SpringMVC Controller接收参数

SpringMVC Controller接收参数

2016.11.10 19:28* 字数 738 阅读 12309评论 6喜欢 44赞赏 2

本文中Controller的开发环境如下表格所示

系统/工具版本号
OSWindows 7 Home Basic
Java1.7.0_79
EclipseMars.1 Release (4.5.1)
Maven3.3.9
Postman4.8.1
Tomcat7.0.47

Maven对应Pom主要依赖配置

 
  1. <dependency>

  2. <groupId>org.springframework</groupId>

  3. <artifactId>spring-webmvc</artifactId>

  4. <version>4.3.1.RELEASE</version>

  5. </dependency>

  6. <dependency>

  7. <groupId>org.springframework</groupId>

  8. <artifactId>spring-web</artifactId>

  9. <version>4.3.1.RELEASE</version>

  10. </dependency>

基本数据类型

SpringMVC Controller各方法参数绑定首先支持Java所有基本类型(包括: byteshortintlongfloatdoublecharstringboolean),以及基本类型对应封装高级类(包括:StringBuilderStringBuffer)。

代码示例如下所示(这里仅以intInteger类型做例子,其他类型实现方式与此类同):

 
  1. @Controller

  2. @RequestMapping("param")

  3. public class ParamController {

  4. @RequestMapping(value="/int", method=RequestMethod.POST)

  5. @ResponseBody

  6. public String requestInt(int param) {

  7. return "Request successful. Post param : Int - " + param;

  8. }

  9. @RequestMapping(value="/integer", method=RequestMethod.POST)

  10. @ResponseBody

  11. public String requestInteger(Integer param) {

  12. return "Request successful. Post param : Integer - " + param;

  13. }

  14. //......

  15. }

  16.  

集合类型

  • List

除了基本类型,Spring Controller各方法参数绑定还支持集合类型,这里拿常用的ListMap举例,如果直接拿集合类作为绑定参数,写法上与基本类型类似,不同的是需要在参数处增加注解@RequestParam(),具体代码示例如下所示:

 
  1. @RequestMapping(value="/list", method=RequestMethod.POST)

  2. @ResponseBody

  3. public String requestList(@RequestParam("listParam[]") List<String> param) {

  4. return "Request successful. Post param : List<String> - " + param.toString();

  5. }

  6.  

对应Postman的请求如下:

Postman Post请求及应答图示.png

对应Ajax的请求如下:

 
  1. var strList = new Array();

  2. strList.push("field1");

  3. strList.push("field2");

  4. function postList() {

  5. $.ajax({

  6. type:"POST",

  7. url:"http://localhost:8080/Learn-Spring-MVC/list",

  8. data:{"listParam" : strList},

  9. dataType:"json",

  10. success:function(result) {

  11. //......

  12. },

  13. error:function(result) {

  14. //......

  15. }

  16. });

  17. }

  18.  

关于List做为Controller参数,除了String本人还测试Integer以及Double类型,其他类型未作测试。这里面@RequestParam()必须增加"listParam[]"如果你的Web端是别的名字,换成相应名称即可,如果只用@RequestParam注解的话,请求会接到HTTP Status 400 - Required List parameter 'xxx' is not present的提示信息。

  • Map

Map类型作为参数,只需要使用@RequestParam注解即可,这里Map对应的key-value基本是String类型,value可以为Object,代码示例如下所示:

 
  1. @RequestMapping(value="/map", method=RequestMethod.POST)

  2. @ResponseBody

  3. public String requestList(@RequestParam Map<String, Object> param) {

  4. return "Request successful. Post param : Map - " + param;

  5. }

  6.  

对应Postman的请求如下:

Postman Post请求及应答图示.png

对应Ajax的请求如下:

 
  1. function postMap() {

  2. $.ajax({

  3. type:"POST",

  4. url:"http://localhost:8080/Learn-Spring-MVC/map",

  5. data:{field1:"field1",field2:1},

  6. dataType:"json",

  7. success:function(result) {

  8. //......

  9. },

  10. error:function(result) {

  11. //......

  12. }

  13. });

  14. }

  15.  

Map作为参数的话,会把Ajax请求中的全部数据转换为key-value存入Map对应中,具体可参见Spring官方文档关于@RequestParam部分

自定义类型

自定义People类,具体类内容如下代码所示:

 
  1. public class People implements Serializable{

  2. private static final long serialVersionUID = 1L;

  3. private String name;

  4. private short age;

  5. private Map<String, String> relationship;

  6. public String getName() {

  7. return name;

  8. }

  9. public void setName(String name) {

  10. this.name = name;

  11. }

  12. public short getAge() {

  13. return age;

  14. }

  15. public void setAge(short age) {

  16. this.age = age;

  17. }

  18. public Map<String, String> getRelationship() {

  19. return relationship;

  20. }

  21. public void setRelationship(Map<String, String> relationship) {

  22. this.relationship = relationship;

  23. }

  24. @Override

  25. public String toString() {

  26. return "People [name=" + name + ", age=" + age + ", relationship=" + relationship + "]";

  27. }

  28. }

  29.  

对应Controller方法代码如下所示,主要的不同点就是需要在自定义类前添加@ModelAttribute注解:

 
  1. @RequestMapping(value="/people", method=RequestMethod.POST)

  2. @ResponseBody

  3. public String requestPeople(@ModelAttribute People people) {

  4. return "Get request is successful. Post param : User Class - " + people.toString();

  5. }

  6.  

对应Ajax的请求如下:

 
  1. var people = {

  2. name:"Heacewalker",

  3. age:25,

  4. relationship:{"boss":"BigBoss"}

  5. }

  6. function postClick() {

  7. $.ajax({

  8. type:"POST",

  9. url:"http://localhost:8080/Learn-Spring-MVC/people",

  10. data:people,

  11. dataType:"json",

  12. success:function(result) {

  13. //......

  14. },

  15. error:function(result) {

  16. //......

  17. }

  18. });

  19. }

  20.  

对应Postman的请求如下:

Postman Post请求及应答图示.png

这里再说一下,如果自定义类中包含集合的话,要如何处理参数的问题,首先定义包含集合的类,具体代码如下所示:

 
  1. public class Address {

  2. private String code;

  3. private String address;

  4. public String getCode() {

  5. return code;

  6. }

  7. public void setCode(String code) {

  8. this.code = code;

  9. }

  10. public String getAddress() {

  11. return address;

  12. }

  13. public void setAddress(String address) {

  14. this.address = address;

  15. }

  16. @Override

  17. public String toString() {

  18. return "Address [code=" + code + ", address=" + address + "]";

  19. }

  20. }

  21.  

 
  1. public class Link {

  2. private List<Address> address;

  3. public List<Address> getAddress() {

  4. return address;

  5. }

  6. public void setAddress(List<Address> address) {

  7. this.address = address;

  8. }

  9. @Override

  10. public String toString() {

  11. return "Link [address=" + address + "]";

  12. }

  13. }

  14.  

最后是Controller部分的代码,示例如下:

 
  1. @RequestMapping(value="/link", method=RequestMethod.POST)

  2. @ResponseBody

  3. public String requestLink(@ModelAttribute Link link) {

  4. return "Get request is successful. Post param : User Class - " + link.toString();

  5. }

  6.  

Postman Post请求及应答图示.png

对应Postman的请求如下:

Postman Post请求及应答图示.png

对应Ajax的请求如下:

 
  1. <form onsubmit="return PostData()">

  2. <input name="address[0].address" value="AKB"/>

  3. <input name="address[0].code" value="48"/>

  4. <input name="address[1].address" value="HKT"/>

  5. <input name="address[1].code" value="48"/>

  6. <input type="submit" value="提交"/>

  7. </form>

  8. ......

  9. function PostData() {

  10. $.ajax({

  11. type:"POST",

  12. url:"http://localhost:8080/Learn-Spring-MVC/link",

  13. data:'',

  14. success:function(result) {

  15. //......

  16. },

  17. error:function(result) {

  18. //......

  19. }

  20. });

  21. }

  22.  

通过URL路径传递参数并接收,具体Controller代码如下所示:

 
  1. @RequestMapping(value="/path/{key}/{value}", method=RequestMethod.POST)

  2. @ResponseBody

  3. public String requestPath(@PathVariable String key, @PathVariable String value) {

  4. return "Get request is successful. Path param : key - " + key + "; value - " + value;

  5. }

  6.  

对应Postman的请求如下:

Postman Post请求及应答图示.png

最后,说一下用HttpServletRequest接收请求参数的方法,Controller代码如下所示,Controller接收到的参数值均为String类型:

 
  1. @RequestMapping(value="/request", method=RequestMethod.POST)

  2. @ResponseBody

  3. public String request(HttpServletRequest arg0, HttpServletResponse arg1) {

  4. return "Get request is successful. Post param : param1 - " + arg0.getParameter("param1") +

  5. "; param2 - " + arg0.getParameter("param2") +

  6. "; param3 - " + arg0.getParameter("param3");

  7. }

  8.  

对应Ajax请求:

 
  1. var idList = new Array();

  2. idList.push("1");

  3. idList.push("2");

  4. idList.push("3");

  5. function postTest() {

  6. $.ajax({

  7. type:"POST",

  8. url:"http://localhost:8080/Learn-Spring-MVC/request",

  9. data:{"param1":"test","param2":2,"param3":JSON.stringify(idList)},

  10. dataType:"json",

  11. success:function(result) {

  12. //......

  13. },

  14. error:function(result) {

  15. //......

  16. }

  17. });

  18. }

  19.  

这里idList是集合类型,如果不是用JSON.stringify()进行转换的话,到Controller层接收到的参数值对应则为null。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值