XML Validation From Schema In Servlet Filter

M

MJ

I am attempting to write a ServletFilter in Java/J2EE that checks if
the incoming data is valid according to a schema. If errors occur, I
want to return the error list and not proceed down the chain. If no
errors, the next in the servlet chain should receive the original XML.

The data in the input stream has already been consumed by the XML
parser.
What is the easiest way to validate the XML and keep the source xml
available for the next link in the chain?

something like...

public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// we want to stream the input stream thru a SAX validation and
check for errors
ValidationHandler handler = new ValidationHandler();
try {
XMLReader reader =
XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
reader.setFeature("http://xml.org/sax/features/validation",
true);
reader.setFeature("http://apache.org/xml/features/validation/schema",
true);
reader.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation",
"test" + test.xsd);
reader.setErrorHandler(handler);
reader.setContentHandler(handler);

InputStream inStream = request.getInputStream();
InputSource inSource = new InputSource(inStream);
reader.parse(inSource);

if (handler.hasErrors()) {
//write back errors in the response
}
else // parsed successfully now process
chain.doFilter(request, response);

}
catch (SAXException e) {
//write back errors in the response
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,186
Latest member
vinaykumar_nevatia

Latest Threads

Top