Java jaxb,解组后获取原始xml

Java jaxb,解组后获取原始xml,java,jaxb,Java,Jaxb,我有一个简单的小servlet,基本上: void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { JAXBContext jaxb = myContext.getXMLContext().getSearchparamContext(); SearchParams params = null; try {

我有一个简单的小servlet,基本上:

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 "+ request.getRemoteUser(),e);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
...
void doPost(HttpServletRequest请求,HttpServletResponse响应)
抛出ServletException、IOException{
JAXBContext jaxb=myContext.getXMLContext().getSearchparamContext();
SearchParams params=null;
试一试{
Unmarshaller um=jaxb.createUnmarshaller();
um.setSchema(myContext.getXMLContext().getSearchParamsSchema());
JAXBElement je=(JAXBElement)um.unmarshal(request.getInputStream());
params=je.getValue();
}捕获(JAXBEException e){
logger.log(Level.WARNING,“解析来自用户的xml时出错”+request.getRemoteUser(),e);
senderError(HttpServletResponse.SC\u BAD\u请求);
返回;
}
...

如果解析失败(主要是为了跟踪目的),我有什么方法可以在这里获取原始XML?或者我应该保存到一个文件并从中解组吗?

您可以通过调用
um.unmarshall(new StringReader(str))将
request.getInputStream()
读入
字符串,并解组
字符串

然后在catch子句中也可以访问
字符串
,您可以将
请求.getInputStream()
读入
字符串
,并通过调用
um.unmarshall(new StringReader(str))
来解组该
字符串

然后,在catch子句中也可以访问该
String
,如果要这样做,需要将请求
InputStream
读入临时缓冲区(例如字符串或字节[]),然后通过JAXB传递。如果您的文档很大,那么这可能会影响您的性能,但是如果您的文档很大,那么JAXB无论如何都会很慢

如果您有良好的使用意识,那么这很容易:

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

如果您想这样做,您需要将请求
InputStream
读入临时缓冲区(例如字符串或字节[]),然后通过JAXB传递。如果您的文档太大,那么这可能会影响性能,但是如果您的文档太大,那么JAXB无论如何都会很慢

如果您有良好的使用意识,那么这很容易:

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

如果他有良好的判断力,他应该使用字节[]而不是字符串。破坏xml数据的可能性较小。如果他有良好的判断力,他应该使用字节[]而不是字符串。破坏xml数据的可能性较小。请不要将其读入字符串。如果必须将其读入内存,请使用字节[]。请不要将其读入字符串。如果必须将其读入内存,请使用字节[]。