O'Reilly logo

Java Servlet & JSP Cookbook by Bruce W. Perry

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

13.5. Viewing Internal Resources in a Servlet

Problem

You want to use a servlet to fetch internal resources from a web application for viewing by authenticated users.

Solution

Use the javax.servlet.ServletContext.getResource( String path ) method to generate the input stream from the web resource.

Discussion

A servlet could be used while a web application is in development to provide a view of the deployment descriptor. Web developers often have to double-check web.xml for the values of context-param elements, a servlet's registered name, and other information. Wouldn't it be nice to just request a servlet in the browser to view web.xml?

Example 13-5 opens up web.xml using the ServletContext.getResource( ) method, which returns a java.net.URL object representing the deployment descriptor at the path WEB-INF/web.xml.

The code opens a connection to the XML file by calling the URL object's openConnection( ) method, which returns a java.net.URLConnection object. Then the code buffers the input stream to the resource by wrapping it in a BufferedInputStream:

buf = new BufferedInputStream(urlConn.getInputStream( ));

The urlConn variable refers to a URLConnection.

Tip

If the browser is not savvy about displaying XML files in a readable fashion (Netscape 7.1 and Internet Explorer can display these files properly), you can use XSLT to convert the XML into HTML before it is sent to the browser.

Example 13-5. Displaying the deployment descriptor via a servlet

package com.jspservletcookbook;import ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required