我在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-File有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.]
。
一般here回答了这个问题,但我确信我的文件没有损坏。当我使用相同的文件从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;
}
答案 0 :(得分:1)
@FormParam(“file”)的内容InputStream文件流是file = MyFile.xml而不是它的内容。
答案 1 :(得分:0)
XML标题是否与下面的标题类似?
<?xml version='1.0' encoding='utf-8'?>
答案 2 :(得分:0)
确认验证操作后验证器中使用的InputStream是重置。 没有重置它你可以得到许多奇怪的例外。
我希望它会有所帮助:)