2012-03-24 49 views
0

我是RESTful服务及其在Spring 3上的实现的新手。我希望您的意见能够在客户端在我的服务器中创建新资源时返回类型的最佳实践。Spring 3 RESTful返回POST(创建)

@RequestMapping(method = RequestMethod.POST, 
value = "/organisation", 
headers = "content-type=application/xml") 
@ResponseStatus(HttpStatus.CREATED) 
public ??? createOrganisation(@RequestBody String xml) 
{ 
    StreamSource source = new StreamSource(new StringReader(xml)); 
    Organisation organisation = (Organisation) castorMarshaller.unmarshal(source); 
    // save 
    return ???; 
} 

回答

0

一个简单的选择是javax.ws.rs.core.Response,在Java EE自己的RESTful服务包中找到。它 - 简单地说 - 告诉Web服务器应该对HTTP请求应答的内容。 例如:

if (organisation != null) 
    return Response.ok().build(); 
else 
    return Response.serverError().build(); 

定制响应头和其他外来之类的东西都可能与返回类型太多,但我不认为这如同“最佳实践”。


呃,我错过了@ResponseStatus(HttpStatus.CREATED)......我想我的答案是没有太大的帮助。

也许这将帮助而不是:How to return generated ID in RESTful POST?

+0

这将帮助http://stackoverflow.com/questions/12837907/what-to-return-if-spring-mvc-controller-method-doesnt-return-value – Xiangyu 2015-08-24 09:35:02

0

它是包裹在ResponseEntity一个好主意,返回新创建的实体(与生成的ID)。您也可以根据操作结果在ResponseEntity中设置HttpStatus。

 @RequestMapping(method = RequestMethod.POST, 
     value = "/organization", 
     headers = "content-type=application/xml") 
    public ResponseEntity<Organization> createOrganisation(@RequestBody String xml) { 
      StreamSource source = new StreamSource(new StringReader(xml)); 
      Organization organisation = (Organization) castorMarshaller.unmarshal(source); 
      // save 
      return new ResponseEntity<Organization>(organization, HttpStatus.OK); 
     } 
0

我会去一个ResponseEntity<byte[]>,你将不得不采取对您的控制器方法的响应编组的照顾。注意你基本上是在MVC中取消V,在Spring上有一个MarshallingView,但从经验来看,我认为以前的解决方案更加灵活和易于理解。