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

16.2. Setting ServletContext Attributes in JSPs

Problem

You want to store an object attribute in the ServletContext using a JSP.

Solution

Use the JSTL c:set tag to bind an object to application scope. The JSTL uses the application implicit object to represent the ServletContext, which is also the scope used for the object attributes discussed in the previous recipe.

Discussion

JSP developers can use the JSTL core tags and the jsp:useBean standard action to implement the same functionality as the servlet in Recipe 16.1. Like the program in that recipe, the upcoming JSP stores in the ServletContext an object attribute that contains a java.util.Map type. The Map stores key/value pairs that are accessed by other servlets or JSPs in the same context.

Here are the steps to bind an attribute to the ServletContext using a JSP:

  1. Create the Java class that you will instantiate and bind to the ServletContext.

  2. Place the Java class in the WEB-INF/classes directory, including any package-related directories (if the class is named com.jspservletcookbook.ContextObject then place the class in WEB-INF/classes/com/jspservletcookbook), or in WEB-INF/lib if the class is stored in a JAR file.

  3. Create the JSP that will bind the object attribute to the ServletContext. Store the JSP in the web application's top-level directory.

  4. If the web container does not already provide the JSTL-related components, include them in WEB-INF/lib (see Chapter 23) so that the JSP can use these tag libraries.

First I show the object ...

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