Blankman
Blankman

Reputation: 267020

How to load a xsd file that is stored in my /WEB-INF folder

I want to load a xsd file that is stored in:

/WEB-INF/myxsd.xsd

I will be referencing this in my controller's action, not sure how to do that.

Also, since I will be referencing this all the time, is it possible for me to load it once as oppose to per request?

public String create() {

   // load xsd file here 

}

Do you use a relative path or full path?

Update

I have this code already that needs the xsd file where I will validate against the schema.

    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = schemaFactory.newSchema(schemaFile);

schemaFile is what I need help initializing, it seems newSchema has a few overloads (file, URI, etc.), but this is a local file so it makes sense to get the file correct? Validator validator = schema.newValidator();

I need help loading this xsd file from my /Web-inf/ folder.

Upvotes: 4

Views: 2989

Answers (2)

beny23
beny23

Reputation: 35018

IMHO, the Spring way of doing this would be to inject a SchemaFactory and Resource into the controller and to initialise the Schema only once. N.B. As per Javadocs Schema is thread-safe.

public class MyController ... implements InitializingBean {
    private SchemaFactory schemaFactory;
    private Schema schema;
    private Resource schemaResource;

    public void setSchemaFactory(SchemaFactory schemaFactory) {
        this.schemaFactory = schemaFactory;
    }

    public void setSchemaResource(Resource schemaResource) {
        this.schemaResource = schemaResource;
    }

    public void afterPropertiesSet() throws Exception {
        Source xsdSource = new StreamSource(schemaResource.getInputStream());
        schema = schemaFactory.newSchema(xsdSource);
    }

    public void create() {
        // use schema
    }
}

And the spring config:

<bean id="schemaFactory" 
      class="javax.xml.validation.SchemaFactory"
      factory-method="newInstance">
    <constructor-arg>
        <util:constant static-field="javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI"/>
    </constructor-arg>
</bean>

<bean id="myController" class="...MyController">
    <property name="schemaFactory" ref="schemaFactory" />
    <property name="resource" value="/WEB-INF/myxsd.xsd" />
</bean>

Upvotes: 1

DoubleMalt
DoubleMalt

Reputation: 1283

The ServletContext has a method getRealPath(). So servletContext.getRealPath("WEB-INF") will give you the absolute path of the WEB-INF directory.

Use ServletContext#getResourceAsStream().

To load it only once per request, you can create a field and load it lazily.

But even better would be to load it as context attribute with a lifecycle listener.

Upvotes: 2

Related Questions