bob*_*lls 6 java validation jax-ws jaxb unmarshalling
我们将JAX-WS与JAXB结合使用来接收和解析XML Web服务调用.这都是基于注释的,即我们从未在代码中掌握JAXBContext.我需要在unmarshaller上设置一个自定义ValidationEventHandler,这样如果不接受特定字段的日期格式,我们就可以捕获错误并在响应中报告一些好的东西.我们在相关字段上有一个XMLJavaTypeAdapter,它进行解析并抛出异常.我无法看到如何使用我们拥有的基于注释的配置将ValidationEventHandler设置到unmarshaller上.有任何想法吗?
注意:与此评论相同的问题目前尚未得到答复.
上周我一直在努力解决这个问题,最后我找到了一个可行的解决方案。诀窍在于 JAXB 在使用 @XmlRootElement 注释的对象中查找 beforeUnmarshal 和 afterUnmarshal 方法。
..
@XmlRootElement(name="MSEPObtenerPolizaFechaDTO")
@XmlAccessorType(XmlAccessType.FIELD)
public class MSEPObtenerPolizaFechaDTO implements Serializable {
..
public void beforeUnmarshal(Unmarshaller unmarshaller, Object parent) throws JAXBException, IOException, SAXException {
unmarshaller.setSchema(Utils.getSchemaFromContext(this.getClass()));
unmarshaller.setEventHandler(new CustomEventHandler());
}
public void afterUnmarshal(Unmarshaller unmarshaller, Object parent) throws JAXBException {
unmarshaller.setSchema(null);
unmarshaller.setEventHandler(null);
}
Run Code Online (Sandbox Code Playgroud)
使用此 ValidationEventHandler:
public class CustomEventHandler implements ValidationEventHandler{
@Override
public boolean handleEvent(ValidationEvent event) {
if (event.getSeverity() == event.ERROR ||
event.getSeverity() == event.FATAL_ERROR)
{
ValidationEventLocator locator = event.getLocator();
throw new RuntimeException(event.getMessage(), event.getLinkedException());
}
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
}
这是在 Utility 类中创建的 getSchemaFromContext 方法:
@SuppressWarnings("unchecked")
public static Schema getSchemaFromContext(Class clazz) throws JAXBException, IOException, SAXException{
JAXBContext jc = JAXBContext.newInstance(clazz);
final List<ByteArrayOutputStream> outs = new ArrayList<ByteArrayOutputStream>();
jc.generateSchema(new SchemaOutputResolver(){
@Override
public Result createOutput(String namespaceUri,
String suggestedFileName) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
outs.add(out);
StreamResult streamResult = new StreamResult(out);
streamResult.setSystemId("");
return streamResult;
}
});
StreamSource[] sources = new StreamSource[outs.size()];
for (int i = 0; i < outs.size(); i++) {
ByteArrayOutputStream out = outs.get(i);
sources[i] = new StreamSource(new ByteArrayInputStream(out.toByteArray()), "");
}
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
return sf.newSchema(sources);
}
Run Code Online (Sandbox Code Playgroud)