In the Use cases section we have shown how to use a ready-made DocumentRequestHandler implementation from the HTMLDemo class of the LWUITDemo example application (available in in the <Nokia SDK 2.0 for Java installation directory>\plugins\lwuit\examples directory.)
In this section, we will create our own simple implementation that reads from files stored in the JAR. Our implementation will accept URLs with the file:// protocol only, and fetch them from the JAR:
import com.sun.lwuit.html.DocumentInfo; import com.sun.lwuit.html.DocumentRequestHandler; import java.io.ByteArrayInputStream; import java.io.InputStream; class FileRequestHandler implements DocumentRequestHandler { public InputStream resourceRequested(DocumentInfo docInfo) { // Get the full URL from the docInfo String url=docInfo.getUrl(); if (!url.startsWith(“file://”)) { // We support only files return getErrorStream(“This handler handles files only.”) } if (docInfo.isPostRequest()) { // We don't support POST return getErrorStream(“GET requests only please!”); } url=url.substring(7); // Cut the file:// return getClass().getResourceAsStream(url); } // Utility method to get a stream out of a string private InputStream getErrorStream(String err) { err=”<html><body>”+err+”</body></html>”; ByteArrayInputStream bais = new ByteArrayInputStream(err.getBytes()); return bais; } }
As we can see, the implementation is quite simple. It uses the getResourceAsStream method to obtain an InputStream of the file and send it over, but before that it queries the passed DocumentInfo object to get some information on the requested page. This object is explained in detail in the DocumentInfo section.