java - 使用 JAXB 的 Jersey Web 服务中的 xml 语法无效

标签 java xml web-services rest jaxb

我正在使用 jersey Web 服务,它将 POST 请求作为 xml 消费,并以 xml 形式生成响应。 我正在使用 JAXB 将 xml 编码/解码到 Java bean 中。这里的“TestCall”是一个类,它存储请求中指定的所有属性,但如果请求中的 XML 格式错误(即缺少结束标记),我需要在响应 XML 中返回错误代码。那么如何处理这些情况呢?

这是我的代码:

@POST 
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
@Path("/testCall")
@Override
public TestCallOutput postCall(TestCall testCall) 
    return myService.acceptCallData(testCall);
}

我使用以下 2 个类编码 xml:

import javax.xml.bind.annotation.XmlRegistry;
@XmlRegistry
public class ObjectFactory {


/**
 * Create a new ObjectFactory that can be used to create new instances of schema 
 * 
 */
public ObjectFactory() {
}

/**
 * Create an instance of {@link TestCall }
 * 
 */
public Ivrcall createTestcall() {
    return new Testcall();
}

}

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {

})
@XmlRootElement(name = "testcall")
public class TestCall {

/** The method. */
@XmlElement(required = true)
protected String method;

/** The dateref. */
@XmlElement(required = true)
protected String dateref;

/** The timeref. */
@XmlElement(required = true)
protected String timeref;

/** Getters and Setters of elements 
... */
}    

我需要以 xml 格式返回响应,如下所示: <testcall> <status>ERROR</status> <msgid>0001</msgid> <msgtxt>INVALID XML DOCUMENT</msgtxt> </testcall>

最佳答案

堆栈应该通过向客户端返回 500 错误来为您处理此问题。您不需要做任何工作。

编辑:如果你坚持要实现这个(如果我是你,我会推迟,除非你需要遵守现有的接口(interface)),你应该添加一个 JAX-WS 处理程序(javax.xml .ws.handler.Handler)并重写 handleFault 以检查 JAX-WS 在无法解码传入消息时抛出的特定异常。然后在处理程序中创建响应 XML。

关于java - 使用 JAXB 的 Jersey Web 服务中的 xml 语法无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25761257/

相关文章:

java - 如何在CXF中处理来自外部系统的SOAP故障?

java - 排序集合的最快方法

c# - 如何防止 XmlReader 跳到文件末尾,或者如何重置阅读器

c# - 从流加载 XmlDocument 时缺少根元素

c++ xml字符串-缺少所需的空格

java - 如何在使用 Axis 1.4 wsdl2java 生成的客户端时获取 SOAP 消息

java - 将使用 SOAP 从 (C# .net) Web 服务接收的对象转换为 Android 中的字符串数组

java - Spring 中同一个 jms 容器中的多个 OracleAQ 监听器?

java - NetBeans 和 Java : what to add to version control?

java - 未能在 Spring 启动Gradle项目