我在我的 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;
}