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.xerce s.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
}
}