开发者

jaxb, get the original xml after unmarshalling

开发者 https://www.devze.com 2022-12-13 07:59 出处:网络
I\'ve a simple little servlet, basically: void doPost(HttpServletRequest request, HttpServletResponse response)

I've a simple little servlet, basically:

void doPost(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException {
    JAXBContext jaxb = myContext.getXMLContext().getSearchparamContext();
    SearchParams params = null;
     try {
        Unmarshaller um = jaxb.createUnmarshaller();
        um.setSchema(myContext.getXMLContext().getSearchParamsSchema()); 
         JAXBElement<SearchParams> je = (JAXBElement<SearchParams>) um.unmarshal(request.getInputStream());
        params = je.getValue();
    } catch (JAXBException e) {
        logger.log(Level.WARNING,"Error parsing xml from user开发者_如何学C "+ request.getRemoteUser(),e);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
...

Is there any way I can get hold of the original XML here, if parsing fails - mostly for tracing purposes. Or should I just save to a file and unmarshal from that ?


If you want to do that, you'll need to read the request InputStream into a temporary buffer (e.g. a String or a byte[]), and then pass that through JAXB. If your documents are large, then this could hurt your performance, but then if your documents are large, then JAXB is going to be slow anyway.

If you have the good sense to use Apache Commons IO, then this is easy:

String buffer = IOUtils.toString(request.getReader());
Object obj = jaxbContext.createUnmarshaller().unmarshal(new StringReader(buffer));
// do something else with the buffer here


You can read the request.getInputStream() into a String, and unmarshal that String, by calling um.unmarshall(new StringReader(str)); Then that String will also be accessible in the catch-clause

0

精彩评论

暂无评论...
验证码 换一张
取 消