从MessageBodyReader类访问WebContent文件夹中的xsd文件

时间:2013-07-20 16:38:15

标签: java xsd jax-rs getresource web-content

在JAX-RS服务中,我不想提供XmlValidatonReader来验证传入的XML文档与位于WebContent目录中的现有xsd文件。

enter image description here

xsd文件需要位于WebContent文件夹中,因为客户端应该可以访问它。为了验证传入的XML文件,我需要xsd资源:/WebContent/Category.xsd

如何从src/at/fhj/ase/XmlValidationReader.java

加载此内容

1 个答案:

答案 0 :(得分:0)

所以我带它去运行。

@Provider
@Consumes(MediaType.APPLICATION_XML)
public class XmlValidationReader implements MessageBodyReader<Category> {

    protected Providers providers;
    protected ServletContext servletContext;
    private final String xsdFileName = "/Category.xsd";
    private Schema schema;

    public XmlValidationReader(@Context Providers providers,
            @Context ServletContext servletContext) {
        this.providers = providers;
        this.servletContext = servletContext;

        try {
            SchemaFactory sf = SchemaFactory
                    .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            File xsd = new File(servletContext.getRealPath(xsdFileName));
            schema = sf.newSchema(xsd);
        } catch (Exception e) {
            throw new RuntimeException(
                    "Unable to create XSD validation schema", e);
        }
    }

    @Override
    public boolean isReadable(Class<?> type, Type genericType,
            Annotation[] annotations, MediaType mediaType) {
        ...
    }


    @Override
    public Category readFrom(Class<Category> type, Type genericType,
            Annotation[] annotations, MediaType mediaType,
            MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
            throws IOException, WebApplicationException {
        ...
    }