我正在使用 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/