【问题标题】:Validation of JAX-RS request with JAX-B object as parameter使用 JAX-B 对象作为参数验证 JAX-RS 请求
【发布时间】:2016-08-14 16:34:54
【问题描述】:

我尝试使用 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 status 400,但我得到了HTTP status 204

研究:

我找到了Schema validation

  1. 使用 jaxrs:schemaLocations 元素

[...]

  1. 单独配置提供程序

[...]

  1. 使用 SchemaValidation 注释

但我没有 XSD 文件(只有 JAX-B 类)。

有没有办法在没有 XSD 文件的情况下验证 JAX-B 对象?

【问题讨论】:

  • 如果您使用的是 CXF 3.x,它支持bean validation。太糟糕了,文档中的链接是死链接。我不使用 CXF,所以在配置这个方面我真的帮不上什么忙

标签: java jaxb jax-rs cxf


【解决方案1】:

一个不好的解决方法是使用 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-29
    • 1970-01-01
    • 1970-01-01
    • 2016-08-20
    • 2011-04-22
    • 2011-02-11
    • 2012-06-16
    相关资源
    最近更新 更多