Spring 注解之@RequestBody和@PostMapping

@RequestBody的使用

  注解@RequestBody用于接收前端传递给后端的、JSON对象的字符串,这些数据位于请求体中,适合处理的数据为非Content-Type: application/x-www-form-urlencoded编码格式的数据,比如:application/json、application/xml等类型的数据。就application/json类型的数据而言,使用注解@RequestBody可以将body里面所有的JSON字符串绑定到后端相应的Java Bean上,后端再进行数据解析和业务操作。需要格外注意的是,JSON字符串中的key必须对应Java Bean中的属性名;否则,无法接收到相关key的值。

  GET请求中,因为没有请求体,所以@RequestBody并不适用。POST请求中,必须要在请求头中声明数据的类型Content-Type。Spring MVC通过使用系统默认配置的HttpMessageConverters解析请求体中的数据,然后把数据绑定到相应的Java Bean上。

   温馨提示:一个请求,只可以使用一个@RequestBody注解,却可以使用多个@RequestParam注解。

@RestController
@RequestMapping("/user")
public class UserController {
    @PostMapping("/testRequestBody")
    public User testRequestBody(@RequestBody User user){
        return user;
    }

    /**
     * 同时使用 @RequestBody 与 @RequestParam()
     * http://localhost:8087/wiener/user/testRequestBody?token=IamToken
     * @param user
     * @param token
     * @return
     * @throws Exception
     */
    @PostMapping("/testRequestBodyAndParam")
    public User testRequestBodyAndParam(@RequestBody User user, @RequestParam("token") String token) throws Exception {
        user.setRemark(token);
        return user;
    }
}

  其中,Java Bean User定义如下:


import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.stereotype.Component;

import java.io.Serializable;

/**
 * @author Wiener
 */
@Setter
@Getter
@ToString
@Component
public class User implements Serializable {
    private static final long serialVersionUID = 4268287310462519889L;
    private Long id;
    private int age;
    private String name;
    private String remark;

    public User() {
    }
    public User(Long id, int age, String name) {
        super();
        this.id = id;
        this.age = age;
        this.name = name;
    }

}

  启动项目,使用Postman模拟前端HTTP请求,测试结果如下,说明两个注解可以同时使用。

Spring 注解之@PostMapping

  @PostMapping是一个组合注解,在Spring framework 4.3作为@RequestMapping(method = RequestMethod.POST)的变体引入,它将HTTP Post请求映射到特定的处理方法上。例如,使用@PosttMapping("/testRequestBody")就等价于@RequestMapping(value ="/testRequestBody",method = RequestMethod.POST),显然,这可以精简我们的代码。

小结

  在GET请求中,不能使用@RequestBody。在POST请求,可以使用@RequestBody和@RequestParam,但是如果使用@RequestBody,对于参数转化的约定,前后端必须统一。

原文地址:https://www.cnblogs.com/east7/p/13939235.html