Monday, December 21, 2009

Read and Write objects to request and response

Here is a simple code sample to read/write an object to the HttpServletRequest/Response

/*
* Read an object from the input stream.
*/
private Object readObjectFromRequest ( HttpServletRequest req ) throws IOException {

ObjectInputStream oos = null;
try {
oos = new ObjectInputStream(req.getInputStream());

return oos.readObject();
} catch (ClassNotFoundException ex) {
throw new IOException("Accessing the object threw a ClassNotFoundException : "+ex);
} finally {
if (oos != null) oos.close();
}
}

/*
* Writes an object into the output stream.
*/
private void writeObjectToResponse ( HttpServletResponse resp, Object o ) throws IOException {

ObjectOutputStream oos = new ObjectOutputStream(resp.getOutputStream());
//Write the object into the response output stream and close the stream.
oos.writeObject(o);
oos.close();
}

No comments:

Post a Comment