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

25.3. Accessing the Tomcat JNDI Resource from a JSP

Problem

You want to access a JNDI resource from a JSP.

Solution

Use a filter to place the object in request or session scope. Access the object in the JSP with the c:set and c:out JSTL tags.

Discussion

A nice job for a filter is accessing a JNDI object, then placing a reference to that object in a session for a JSP to use. See Chapter 19 for more information on filters.

Here are the steps needed to use a filter with JNDI and a JSP:

  1. Develop and compile the filter, including a no-arguments constructor.

  2. Use the JNDI API and javax.naming package in the filter to set a session attribute using the JNDI object.

  3. Place the filter in WEB-INF/classes or in a JAR in WEB-INF/lib.

  4. Add filter and filter-mapping elements to web.xml; map the filter to the JSP that will use the JNDI object (Example 25-7).

  5. Create a JSP that uses the session attribute.

Example 25-6 shows the filter. The filter initializes a javax.naming.Context type in its init( ) method (when the servlet container creates the filter instance). The doFilter( ) method grabs a JNDI object and stores the object as a session attribute. The filter chain ends at the JSP to which the filter is mapped; therefore, the JSP has access to the session attribute (i.e., the JNDI object).

Example 25-6. A Filter accesses a JNDI object and sets the object as a session attribute

package com.jspservletcookbook;

import java.io.IOException;import javax.naming.Context; import javax.naming.InitialContext; 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