[ Team LiB ] Previous Section Next Section

Recipe 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 javax.naming.NamingException;

import javax.servlet.*;
import javax.servlet.http.*;

public class JndiTFilter implements Filter {

    private FilterConfig config;
    private Context env;
    
  //No-arguments constructor required for a filter; we've made it
  //explicit here, even though the compiler would have created one
  //in the absence of this or any other constructor
  public JndiTFilter( ) {} 
    
  public void  init(FilterConfig filterConfig)  throws ServletException {
    
      this.config = filterConfig;
      try {
          env = (Context) new InitialContext( ).lookup("java:comp/env");
          env.close( );
      } catch (NamingException ne) { 
          try{ env.close( ); } catch (NamingException nex) {}
          throw new ServletException(ne);
      }
    }
    
  public void doFilter(ServletRequest request, 
    ServletResponse response, FilterChain chain) throws IOException, 
      ServletException {
      
      StockPriceBean spbean = null;
        
      try {
          spbean = (StockPriceBean) env.lookup("bean/pricebean");
      } catch (NamingException ne) { }
        
      HttpServletRequest hRequest = null;
      if (request instanceof HttpServletRequest)
          hRequest = (HttpServletRequest) request;
                 
      HttpSession hSession = hRequest.getSession( );
      if (hSession != null)
          hSession.setAttribute("MyBean",spbean);
        
        
      chain.doFilter(request,response);
    }// doFilter
    
    public void destroy( ){
        /*called before the Filter instance is removed 
        from service by the web container*/
    }
}//Filter

The filter's doFilter( ) method is called each time a client requests the JSP, so each client is associated with a different bean instance. In other words, each session stores its own bean instance.

The JSP could then remove the session attribute (if it was not going to be used again) to conserve server resources. See Chapter 16 for recipes on setting and removing session attributes.


Example 25-7 shows the filter and filter-mapping elements that you can add to the deployment descriptor. This causes the servlet container to create an instance of the filter (calling the filter's init( ) method). Then the container calls the filter's doFilter( ) method whenever it receives a request matching the URL(s) associated with the filter-mapping element.

Example 25-7. The filter and elements for a JNDI-related filter
<!-- start of web.xml -->

<filter>

    <filter-name>JndiTFilter</filter-name>
    <filter-class>com.jspservletcookbook.JndiTFilter</filter-class>

</filter>

<filter-mapping>

    <filter-name>JndiTFilter</filter-name>
    <url-pattern>/jndiJsp.jsp</url-pattern>

 </filter-mapping>

<!-- rest of web.xml -->

Example 25-7 maps the JndiTFilter to the web component at the URL /jndiJsp.jsp. Example 25-8 shows the JSP that uses the session attribute, called "MyBean" to display a stock quote.

Example 25-8. A JSP uses a session attribute originating as a JNDI object
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>

<html>
<head><title>Jndi Bean</title></head>
<body>
<h2>Getting a StockPriceBean object via JNDI...</h2>

<c:set var="priceBean" value="${MyBean}"/>

<%-- set the 'symbol' property to the stock symbol --%>
<c:set target="${priceBean}" property="symbol" value="${param.symbol}"/>

<%-- get the latest price by calling getLatestPrice( ) on the bean object --%>
The latest price: <c:out value="${priceBean.latestPrice}" />

</body>
</html>

Figure 25-3 shows this JSP's output. Example 25-5 in Recipe 25.2 shows the code for the JavaBean that this JSP uses.

Figure 25-3. A JSP uses a session attribute via JNDI to display a stock price
figs/jsjc_2503.gif

See Also

Recipe 25.1 on configuring a JNDI object with Tomcat; Recipe 25.2 on accessing the Tomcat JNDI object from a servlet; Chapter 21 on accessing DataSources with JNDI.

    [ Team LiB ] Previous Section Next Section