我们将JAX-WS与JAXB结合使用来接收和解析XML Web服务调用。都是基于注释的,也就是说,我们永远不会在代码中掌握JAXBContext。我需要在解码器上设置一个自定义ValidationEventHandler,以便如果特定字段的日期格式不被接受,我们可以捕获错误并在响应中报告一些不错的内容。我们在所讨论的字段上有一个XMLJavaTypeAdapter,它进行解析并引发异常。我看不到如何使用已有的基于注释的配置将ValidationEventHandler设置到解码器上。有任何想法吗?

注意:与this comment相同的问题,目前尚未回答。

最佳答案

在过去的一周中,我一直在努力解决这个问题,最后我设法解决了一个可行的解决方案。诀窍在于,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);
  }

使用此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;
      }
}

}

这是在您的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);
  }

关于java - 使用注释时如何在JAXB解码器上设置自定义ValidationEventHandler,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23751249/

10-13 05:24