接着前两篇
继续刨根问底。
@RequestParam
案例:
@PostMapping("/user/login")
public String login(@RequestParam("userName") String userName,
@RequestParam("password") String password) {
System.out.println("userName=" + userName);
System.out.println("password=" + password);
return "ok";
}
访问:
http://localhost:9010/user/login?userName=lawt&&password=123456
@RequestParam源码:
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestParam {
//跟name一样的作用,是name属性的一个别名
@AliasFor("name")
String value() default "";
//绑定本次参数的名称,要跟URL上面的一样
@AliasFor("value")
String name() default "";
//这个参数是不是必须的
boolean required() default true;
//如果本次请求没有携带这个参数,或者参数为空,那么就会启用默认值
String defaultValue() default ValueConstants.DEFAULT_NONE;
}
@RequestParam可以多个使用,接收大参数形式:key=value。
注意
如果在后端方法参数前,指定了@RequestParam()的话,那么前端必须要有对应字段才行(当然可以通过设置该注解的required属性来调节是否必须传),否者会报错;如果参数前没有任何该注解,那么前端可以传,也可以不传。
@PathVariable
案例:
@RequestMapping(value="/user/{id}", method= RequestMethod.GET)
public User getUser(@PathVariable Integer id) {
return new User(id,"Java后端技术栈");
}
访问:
http://localhost:9010//user/10001
返回:
{"userId":10001,"userName":"Java后端技术栈"}
案例:
@RestController
@RequestMapping("/dept/{deptId}")
public class RequestParamDemo {
@RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
public User getUser(@PathVariable Integer deptId,
@PathVariable Integer id) {
System.out.println("deptId="+deptId);
return new User(id, "Java后端技术栈");
}
}
访问:
http://localhost:9010/dept/9001/user/10001
上面代码把URI template 中变量 ownerId的值和deptId的值,绑定到方法的参数上。 若方法参数名称和需要绑定的uri template中变量名称不一致,需要在@PathVariable("name")指定uri template中的名称
案例:
@RestController
@RequestMapping("/dept/{deptId}")
public class RequestParamDemo {
@RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
public User getUser(@PathVariable Integer deptId,
@PathVariable("id") Integer userId) {
System.out.println("deptId="+deptId);
return new User(userId, "Java后端技术栈");
}
}
@PathVariable可以多个使用。
@ResponseBody
案例:
@RestController
public class RequestBodyDemo {
@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public User addUser(@RequestBody User user) {
System.out.println(user);
return user;
}
}
接收参数 格式为请求体里的数据,目前主流的是json,所以本文也是使用json,还有就是在请求的时候,得设置:
Content-Type :application/json;charset=UTF-8
@RequestBody接收请求体中的json数据;不加注解接收URL中的数据并组装为对象:
@RestController
public class RequestBodyDemo {
@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public User addUser(@RequestBody User user, User user1) {
System.out.println(user);
System.out.println(user1);
return user;
}
}
测试:
输出:
@RequestBody与复杂的@RequestParam()同时使用:
@RestController
public class RequestBodyDemo {
@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public User addUser(@RequestBody User user,
@RequestParam("remark") String remark) {
System.out.println(user);
System.out.println("remark=" + remark);
return user;
}
}
测试:
结果:
ok,本次就刨到这里了。