I'm trying to make a RESTful Web Service which implements all four CRUD operations. I got stuck in "Create" because somehow I'm not able to obtain the posted data. Here is the method I wrote. Just as a info, I'm using Jersey RI of JAX-RS + JAXB XML to serialize objects.
Here it is:
@POST
@Consumes("application/xml")
public Response createStudent(InputStream is) {
Student st = this.readStudent(is);
st.setUserId(idCounter.incrementAndGet());
studentDB.put(st.getUserId(), st);
System.out.println("Created student " + st.getUserId());
return Response.created(URI.crea开发者_运维知识库te("/student/"+ st.getUserId())).build();
}
And the readStudent method is below:
protected Student readStudent(InputStream is){
JAXBContext ctx;
Student st = null;
try {
String xml = is.toString();
System.out.println(xml);
ctx = JAXBContext.newInstance(Student.class);
st = (Student) ctx.createUnmarshaller().unmarshal(new StringReader(xml));
return st;
} catch (JAXBException e){
e.printStackTrace();
}
finally { return st; }
}
Can someone give me some light about this? I exhausted every idea to make this works and nothing worked!
Thanks in advance.
I think your problem is the line in which you use the toString()
method to get the string of the InputStream
:
String xml = is.toString();
You should read the data in the input stream and append it to a new string. The toString()
is a string representation of the stream, but not the contents of it. You have to use the read
methods of the InputStream
and append the bytes to a new String
using a StringBuilder
or a StringWriter
.
After sweating hard looking for a answer, I've managed to fix it! It was just a missing dependency to resteasy-jaxb-provider.jar . Without this .jar the servlet wasn't able to do the automatic conversion from POJO to XML and vice-versa
I don't understand why you don't have createStudent(Student student)
instead. The whole idea of jsr311 is for the parameters to also be parsed and given to the function.
EDIT For a second I thought I was confusing things. But I found an example here http://blogs.oracle.com/enterprisetechtips/entry/configuring_json_for_restful_web
@PUT
@Consumes("application/json")
public synchronized void setStatus(StatusInfoBean status) {
...
}
So you don't even need to parse xml or json. This work is already done for you
精彩评论