0

这是我在 RESTful Web 服务中使用的代码片段。我正在向create(Employee entity) 方法发送 JSON 数据。我想从 servlet 请求中获取 JSON 数据。

我使用的 System.out.println(..)方法被打印出来,这意味着stringBuffer不是 NULL;但是在“:”字符之后没有打印任何内容[我正在 glassfish 记录器中检查这个]。此外,POSTed 实体正在正确地保存到数据库中。

我已经在 stackoverflow 和其他网站上搜索了许多与此相关的问题,但到目前为止我没有尝试过任何工作。

public class EmployeeFacadeREST extends AbstractFacade<Employee> {
@Context private HttpServletRequest servletRequest;
@PersistenceContext(unitName = "EmployeePU")
private EntityManager em;

public EmployeeFacadeREST() {
    super(Employee.class);
}


@POST
@Override
@Consumes({"application/xml", "application/json"})

public void create( Employee entity) {
    StringBuffer stringBuffer = null;
    try{
        InputStream body = servletRequest.getInputStream();           
        stringBuffer = new StringBuffer();
        int d;
        while((d = body.read()) != -1){
            stringBuffer.append((char)d);
        }
    }
   
    catch(IOException e){
       
    }
    if(stringBuffer != null){
        System.out.println("the entity is: " + stringBuffer.toString()); // this line gets printed
    }
    super.create(entity);
}
// more code

}

感谢您的洞察力。

4

2 回答 2

2

服务器已经使用了请求正文,以便自动为您将其反序列化为 Employee 实体。您无法再次读取相同的输入流。

于 2012-12-14T00:28:19.807 回答
0

You need to set the 'entity' used by the POST with the value of your stringbuffer.

check the tests or samples of a jersey /glassfish POST .

The POST.entity expects the value u want in the body of the POST.

于 2012-12-14T00:23:02.220 回答