1、接收单个参数
(1)直接接收参数
@RequestMapping("/hello")@RestControllerpublic class HelloSpring {@RequestMapping("/t2")public String t2(String name){return "name=" + name;}}
当没有传入参数时,返回null
(2)包装类接收
如果我们换成int,再次看看结果
@RequestMapping("/hello")@RestControllerpublic class HelloSpring {@RequestMapping("/t2")public String t2(String name){return "name=" + name;}}
postman报错。报错提示我们应该使用包装类
@RequestMapping("/hello")@RestControllerpublic class HelloSpring {@RequestMapping("t4")public String t4(Integer age){return "age=" + age;}}
不传参数时,返回null,不再报错
SpringMVC接收参数时最好使用包装类
2、多个参数
(1)直接写
@RequestMapping("/hello")@RestControllerpublic class HelloSpring {@RequestMapping("t5")public String t5(String name,Integer age){return "name=" + name + ", " + "age=" + age;}}
(2)使用类包装
UserInfo类
public class UserInfo {private String name;private int age;private int id;public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public int getId() {return id;}public void setId(int id) {this.id = id;}@Overridepublic String toString() {return "UserInfo{" +"name='" + name + '\'' +", age=" + age +",language-java">@RequestMapping("/hello")@RestControllerpublic class HelloSpring {@RequestMapping("t6")public String t6(UserInfo userInfo){return userInfo.toString();}}
3、修改参数名
后端接收参数的名字是跟前端保持一致的,因此我们要使用其他参数名时,则要对其进行修改
@RequestMapping("/hello")@RestControllerpublic class HelloSpring {@RequestMapping("t7")public String t7(@RequestParam("name")String username){return "name=" + username;}}//@RequestParam()中所写的是本来的参数名//String后写的是修改后的参数名
但是如果不传入参数,就会报错
可见,上述修改参数是强制传入参数。为了能不报错,我们使参数required为false
@RequestMapping("/hello")@RestControllerpublic class HelloSpring {@RequestMapping("t7")public String t7(@RequestParam(value = "name",required = false)String username){return "name=" + username;}}
这样就算不传入参数,也不会报错
4、接收数组参数
(1)直接传数组
@RequestMapping("/hello")@RestControllerpublic class HelloSpring {@RequestMapping("t8")public String t8(String[] arr){return Arrays.toString(arr);}}
(2)传集合
@RequestMapping("/hello")@RestControllerpublic class HelloSpring {@RequestMapping("t9")public String t9(@RequestParam(value = "list",required = false)List list){return list.toString();}}