文章目录
接受请求参数
1. 简单类型
1.1 请求
1.2 代码
需要保证前端传递的参数名称跟方法的形参名称一致
在mvc底层,对于简单类型参数 是自动进行类型转换
//http://localhost:8080/user/demo5?name=张三&age=18
//需要保证前端传递的参数名称跟方法的形参名称一致
//在mvc底层,对于简单类型参数 是自动进行类型转换
@RequestMapping("/demo5")
public String demo5(String name,Integer age){
System.out.println("name:"+name+",age:"+age);
return "OK";
}
2. 对象类型
2.1 请求
2.2 代码
需要保证前端传递的参数名称跟实体类的属性名称一致
//http://localhost:8080/user/demo6?name=张三&age=18
//需要保证前端传递的参数名称跟实体类的属性名称一致
@RequestMapping("/demo6")
public String demo6(User user){
System.out.println(user);
return "OK";
}
3. 数组类型
3.1 请求
3.2 代码
需要保证前端传递的参数名称跟方法中的数组形参名称一致
//http://localhost:8080/user/demo7?hobby=java&hobby=game
//需要保证前端传递的参数名称跟方法中的数组形参名称一致
@RequestMapping("/demo7")
public String demo7(String[] hobby){
System.out.println(Arrays.toString(hobby));
return "OK";
}
4. 集合类型
4.1 请求
4.2 代码
请求参数名与形参集合名称相同且请求参数为多个,使用
@RequestParam
绑定参数关系
//http://localhost:8080/user/demo8?hobby=java&hobby=game
//请求参数名与形参集合名称相同且请求参数为多个,使用`@RequestParam`绑定参数关系
@RequestMapping("/demo8")
public String demo8(@RequestParam("hobby") List<String> hobby){
System.out.println(Arrays.toString(hobby.toArray()));
return "OK";
}
5. 日期类型
5.1 请求
5.2 代码
接收参数为日期类型,需要使用
@DateTimeFormat
定义参数格式
//http://localhost:8080/user/demo9?updateTime=2022-02-02 02:02:02
//接收参数为日期类型,需要使用`@DateTimeFormat`定义参数格式
@RequestMapping("/demo9")
public String demo9(@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime updateTime){
System.out.println(updateTime);
return "OK";
}
6. json参数
6.1 请求
6.2 代码
SpringMVC也可以接收请求体中的json字符串为参数,并且自动封装为指定对象
此时要求JSON数据键名与形参对象属性名相同,定义POJO类型形参即可接收参数,需要使用@RequestBody
标识
//请求体 发送 json参数
//@RequestBody 标注在方法参数之前,表示从请求体中接收参数(json),并且封装到对象中
//http://localhost:8080/user/demo10
@RequestMapping("/demo10")
public String demo10(@RequestBody User user){
System.out.println(user);
return "OK";
}
7. 路径参数
7.1 请求
7.2 代码
springmvc还支持通过请求路径直接传递参数,后台使用{…}来标识该路径参数,需要使用
@PathVariable
获取
//请求路径中提交的参数,需要使用@PathVariable获取参数
//http://localhost:8080/user/demo11/name/Tom/age/18
@RequestMapping("/demo11/name/{name}/age/{age}")
public String demo11(@PathVariable("name") String name,
@PathVariable("age") Integer age) {
System.out.println("name:" + name + ",age:" + age);
return "OK";
}
8. @RequestParam
@RequestParam标注在方法参数之前,用于对传入的参数做一些限制,常见属性如下:
- name:用于指定前端传入的参数名称
- defaultValue:当参数为非必传参数且前端没有传入参数时,指定一个默认值
8.1 请求
8.2 使用场景
@RequestParam 三种使用场景
1.当后端方法的形参名称跟请求参数不一致的时候,可以使用此注解做一个映射
2.使用此注解可以为参数设置默认值,只有前端不传递的时候,默认值才生效
3.使用此注解可以接收集合数据
8.3 代码
//http://localhost:8080/user/demo12?name=Tom
//@RequestParam 三种使用场景
//1.当后端方法的形参名称跟请求参数不一致的时候,可以使用此注解做一个映射
//2.使用此注解可以为参数设置默认值,只有前端不传递的时候,默认值才生效
//3.使用此注解可以接收集合数据
//@RequestParam 标注的参数默认情况下必须有值(前端传递,设置默认);如果想取消,可以将required属性设置为false。
@RequestMapping("/demo12")
public String demo12(@RequestParam(value = "name",required = false) String username,
@RequestParam(defaultValue = "18") Integer age) {
System.out.println("name:"+username+",age:"+age);
return "OK";
}