RS请求与JAX
我尝试使用JAX-B对象作为参数来验证JAX-RS请求。
码:
JAX-B模型类:
@XmlRootElement(namespace = "http://www.test.com/test")
@XmlAccessorType(value = XmlAccessType.FIELD)
public class TestModel {
@XmlElement(required = true)
private String id;
@XmlElement
private String name;
}
JAX-RS资源类:
@Path("test")
public class TestResource {
@POST
@Consumes({ MediaType.APPLICATION_XML, MediaType.TEXT_XML })
public void create(TestModel testModel) {
// some code
}
}
CXF配置:
<jaxrs:server address="/rest" id="test" staticSubresourceResolution="true">
<jaxrs:serviceBeans>
<ref bean="testResource" />
</jaxrs:serviceBeans>
<jaxrs:providers>
<bean class="org.apache.cxf.jaxrs.provider.JAXBElementProvider" />
</jaxrs:providers>
</jaxrs:server>
例:
请求正文:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:testModel xmlns:ns2="http://www.test.com/test">
<name>testName</name>
</ns2:testModel>
该id
缺失,所以我应该得到一个HTTP状态400,但我得到HTTP状态204。
研究:
我找到了Schema验证:
[...]
[...]
但我没有XSD文件(只有JAX-B类)。
有没有方法来验证没有XSD文件的JAX-B对象?
一个糟糕的解决方法是使用Maven生成XSD文件:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<version>2.2</version>
<executions>
<execution>
<goals>
<goal>schemagen</goal>
</goals>
<phase>generate-resources</phase>
<configuration>
<includes>
<include>*.java</include>
</includes>
<outputDirectory>${basedir}/src/main/resources/</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
并将XSD文件添加到CXF配置中:
<jaxrs:schemaLocations>
<jaxrs:schemaLocation>classpath:schema1.xsd</jaxrs:schemaLocation>
<jaxrs:schemaLocation>classpath:schema2.xsd</jaxrs:schemaLocation>
</jaxrs:schemaLocations>
链接地址: http://www.djcxy.com/p/45623.html
上一篇: RS request with JAX