0

我在我的 REST 应用程序中使用 jaxb。我想通过 Web 表单发送 XML 文件。然后 java 类将解组InputStream.

private void unmarshal(Class<T> docClass, InputStream inputStream)
    throws JAXBException {
    String packageName = docClass.getPackage().getName();
    JAXBContext context = JAXBContext.newInstance(packageName);
    Unmarshaller unmarshaller = context.createUnmarshaller();
    Object marshaledObject = unmarshaller.unmarshal(inputStream);
}

触发该unmarshal方法的 jsp 文件具有form如下所示:

<form action="#" method="POST">
    <label for="id">File</label>
    <input name="file" type="file" />
    <input type="submit" value="Submit" />
</form>

我得到以下 ParserException :

javax.xml.bind.UnmarshalException - with linked exception: [org.xml.sax.SAXParseException: Content is not allowed in prolog.].

这个问题在这里得到了普遍的回答,但我确信我的文件没有损坏。当我从具有相同文件的 java-Class 中调用代码时,不会引发异常。

// causes no exception
File file = new File("MyFile.xml");
FileInputStream fis = new FileInputStream(file);
ImportFactory importFactory = ImportFactory.getInstance();
importFactory.setMyFile(fis);

// but when i pass the file with a web form
@POST
@Produces(MediaType.TEXT_HTML)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response create(@FormParam("file") InputStream filestream) {
    Response response;

    // is a BufferedInputStream, btw    
    LOG.debug("file is type: " + filestream.getClass().getName());

    try { 
        ImportFactory importFactory = ImportFactory.getInstance();
        importFactory.setMyFile(filestream);

        Viewable viewable = new Viewable("/sucess", null);
        ResponseBuilder responseBuilder = Response.ok(viewable);
        response = responseBuilder.build();

    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        ErrorBean errorBean = new ErrorBean(e);
        Viewable viewable = new Viewable("/error", errorBean);
        ResponseBuilder responseBuilder = Response.ok(viewable);
        response = responseBuilder.build();
    }
    return response;
}
4

3 回答 3

1

@FormParam("file") InputStream 文件流的内容是 file=MyFile.xml 而不是它的内容。

于 2011-02-09T14:59:05.103 回答
0

XML 标头是否如下所示?

<?xml version='1.0' encoding='utf-8'?>
于 2010-03-17T11:02:21.803 回答
0

确保您在验证器中使用的 InputStream在验证操作后被重置。如果不重置它,您可能会遇到许多奇怪的异常。

我希望它会有所帮助:)

于 2013-10-30T15:11:22.967 回答