RS request with JAX

I try to validate a JAX-RS request with a JAX-B object as parameter.

Code:

JAX-B model class:

@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 resource class:

@Path("test")
public class TestResource {

    @POST
    @Consumes({ MediaType.APPLICATION_XML, MediaType.TEXT_XML })
    public void create(TestModel testModel) {
        // some code
    }
}

CXF configuration:

<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>

Example:

Request body:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:testModel xmlns:ns2="http://www.test.com/test">
    <name>testName</name>
</ns2:testModel>

The id is missing, so I should get a HTTP status 400, but I get HTTP status 204.

Research:

I found Schema validation:

  • Using jaxrs:schemaLocations element
  • [...]

  • Configuring providers individually
  • [...]

  • Using SchemaValidation annotation
  • but I have no XSD file (only JAX-B classes).

    Is there a way to validate the JAX-B object without a XSD file?


    A bad workaround is to generate XSD file with Maven:

    <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>
    

    and add XSD files to CXF configuration:

    <jaxrs:schemaLocations>
        <jaxrs:schemaLocation>classpath:schema1.xsd</jaxrs:schemaLocation>
        <jaxrs:schemaLocation>classpath:schema2.xsd</jaxrs:schemaLocation>
    </jaxrs:schemaLocations>
    
    链接地址: http://www.djcxy.com/p/45624.html

    上一篇: 杰克逊反序列化:无法识别的领域

    下一篇: RS请求与JAX