在Spring中处理POST请求的REST方法究竟如何工作?

我正在攻读Spring Core认证,我对Spring MVC中的RESTful webapp *练习有一些疑问。

因此,在示例中,我有以下方法创建一个新的Account对象

/** * Creates a new Account, setting its URL as the Location header on the * response. */ @RequestMapping(value = "/accounts", method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) public HttpEntity createAccount(@RequestBody Account newAccount, @Value("#{request.requestURL}") StringBuffer url) { Account account = accountManager.save(newAccount); return entityWithLocation(url, account.getEntityId()); } 

我知道:

  1. 在这种情况下,@ RequestMapping注释指定此方法处理针对/ accounts资源的POST HttpRequest。 我知道它使用POST请求,因为根据REST样式,POST“动词”意味着必须创建新资源。

  2. 我认为这个注释:

      @ResponseStatus(HttpStatus.CREATED) 

    意味着当方法正确结束时(当HttpResponse发送到客户端时),它将201CREATED )放入HttpResponse状态字段。 所以它指定新对象的创建没有问题。 是真的还是我错过了什么?

  3. 该方法的第一个参数是:

     @RequestBody Account newAccount 

    在我看来,阅读文档时,此参数与Web请求的主体有关。 请求的主体通过HttpMessageConverter传递,以根据请求的内容类型解析方法参数。

    那究竟是什么意思呢? 我认为这意味着在我的HttpRequest的主体中 ,我有JSON格式的Account对象,并且使用Jackson将其转换为经典的Account Java对象。 是对的还是我错过了什么?

  4. 该方法的第二个参数是:

    @Value(“#{request.requestURL}”)StringBuffer url

    究竟意味着什么?

  5. 然后该方法将获得的对象保存在数据库中。

  6. 最后它返回:

     return entityWithLocation(url, account.getEntityId()); 

    究竟是什么意思? 什么回来了? 在哪里? 结果是不是进入了HttpResponse?

编辑1:

entityWithLocation()方法定义在前一个方法的同一个类中,这是它的代码:

 private HttpEntity entityWithLocation(StringBuffer url, Object resourceId) { // Configure and return an HttpEntity object - it will be used to build // the HttpServletResponse HttpHeaders headers = new HttpHeaders(); headers.setLocation(getLocationForChildResource(url, resourceId)); return new HttpEntity(headers); } 

以下是我对你的问题的理解。

  1. @RequestBody帐户newAccount

关于这一点,您的理解是正确的。

  1. @Value(“#{request.requestURL}”)StringBuffer url

它等同于request.getRequestURL(); 请参阅API

  1. entityWithLocation(url,account.getEntityId())

根据此方法中的代码。 它返回HttpEntity Object,它表示http请求或响应实体( which includes headers and body ),在您的情况下它是response 。 在方法内部,您添加了创建的resource(account)location