SpringMVC-五种类型参数传递

推荐先阅读Spring全家桶

普通参数

GET http://localhost/commonParamDifferentName?name=张三&age=18
@RequestMapping("/commonParamDifferentName")
@ResponseBody
public String commonParamDifferentName(@RequestPaam("name") String userName , int age){
System.out.println("普通参数传递 userName ==> "+userName);
System.out.println("普通参数传递 age ==> "+age);
return "{'module':'common param different name'}";
}

@RequestPaam("name") 解决参数不一致问题

注意:写上@RequestParam注解框架就不需要自己去解析注入,能提升框架处理性能

POJO类型参数

public class User {
private String name;
private int age;
//setter...getter...略
}
GET http://localhost/commonParamDifferentName?name=zhangxin&age=18
//POJO参数:请求参数与形参对象中的属性对应即可完成参数传递
@RequestMapping("/pojoParam")
@ResponseBody
public String pojoParam(User user){
System.out.println("pojo参数传递 user ==> "+user);
return "{'module':'pojo param'}";
}

嵌套POJO类型参数

public class Address {
private String province;
private String city;
//setter...getter...略
}
public class User {
private String name;
private int age;
private Address address;
//setter...getter...略
}
GET http://localhost/commonParamDifferentName?name=zhangxin&age=18&address.city=hangzhou&address.province=zhejiang
//POJO参数:请求参数与形参对象中的属性对应即可完成参数传递
@RequestMapping("/pojoParam")
@ResponseBody
public String pojoParam(User user){
System.out.println("pojo参数传递 user ==> "+user);
return "{'module':'pojo param'}";
}

数组类型参数

GET http://localhost/arrayParam?likes=game&likes=music&likes=travel
//数组参数:同名请求参数可以直接映射到对应名称的形参数组对象中
@RequestMapping("/arrayParam")
@ResponseBody
public String arrayParam(String[] likes){
System.out.println("数组参数传递 likes ==> "+ Arrays.toString(likes));
return "{'module':'array param'}";
}

集合类型参数

GET http://localhost/arrayParam?likes=game&likes=music&likes=travel
//集合参数:同名请求参数可以使用@RequestParam注解映射到对应名称的集合对象中作为数据
@RequestMapping("/listParam")
@ResponseBody
public String listParam(@RequestParam List<String> likes){
System.out.println("集合参数传递 likes ==> "+ likes);
return "{'module':'list param'}";
}

知识点1:@RequestParam

名称 @RequestParam
类型 形参注解
位置 SpringMVC控制器方法形参定义前面
作用 绑定请求参数与处理器方法形参间的关系
相关参数 required:是否为必传参数
defaultValue:参数默认值