@RequestMapping("/hello")
@RestController
public class HelloSpring {
@RequestMapping("/t2")
public String t2(String name){
return "name=" + name;
}
}
?当没有传入参数时,返回null
如果我们换成int,再次看看结果
@RequestMapping("/hello")
@RestController
public class HelloSpring {
@RequestMapping("/t2")
public String t2(String name){
return "name=" + name;
}
}
postman报错。报错提示我们应该使用包装类
@RequestMapping("/hello")
@RestController
public class HelloSpring {
@RequestMapping("t4")
public String t4(Integer age){
return "age=" + age;
}
}
不传参数时,返回null,不再报错?
SpringMVC接收参数时最好使用包装类
@RequestMapping("/hello")
@RestController
public class HelloSpring {
@RequestMapping("t5")
public String t5(String name,Integer age){
return "name=" + name + ", " + "age=" + age;
}
}
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;
}
@Override
public String toString() {
return "UserInfo{" +
"name='" + name + '\'' +
", age=" + age +
", id=" + id +
'}';
}
}
@RequestMapping("/hello")
@RestController
public class HelloSpring {
@RequestMapping("t6")
public String t6(UserInfo userInfo){
return userInfo.toString();
}
}
后端接收参数的名字是跟前端保持一致的,因此我们要使用其他参数名时,则要对其进行修改
@RequestMapping("/hello")
@RestController
public class HelloSpring {
@RequestMapping("t7")
public String t7(@RequestParam("name")String username){
return "name=" + username;
}
}
//@RequestParam()中所写的是本来的参数名
//String后写的是修改后的参数名
但是如果不传入参数,就会报错
可见,上述修改参数是强制传入参数。为了能不报错,我们使参数required为false
@RequestMapping("/hello")
@RestController
public class HelloSpring {
@RequestMapping("t7")
public String t7(@RequestParam(value = "name",required = false)String username){
return "name=" + username;
}
}
这样就算不传入参数,也不会报错
@RequestMapping("/hello")
@RestController
public class HelloSpring {
@RequestMapping("t8")
public String t8(String[] arr){
return Arrays.toString(arr);
}
}
@RequestMapping("/hello")
@RestController
public class HelloSpring {
@RequestMapping("t9")
public String t9(@RequestParam(value = "list",required = false)List<String> list){
return list.toString();
}
}