ProblemYou want to access or remove a ServletContext attribute in a JSP. SolutionUse the c:out JSTL core tag to display the value of an attribute and the c:remove tag to remove the attribute from the ServletContext . DiscussionBy now you are probably familiar with the object attribute that the previous recipes stored in the ServletContext under the name com.jspservletcookbook.ContextObject . If you are not, Recipe 16.1 and Recipe 16.2 show the source code for this class and how it is bound as an attribute to a servlet and a JSP. This recipe shows the JSTL tags that you can use in JSP code to access this attribute and optionally remove or unbind it. Example 16-6 includes the taglib directive that is required for using JSTL 1.0 tags in a JSP. The c:out tag then accesses the ServletContext attribute in the tag's value attribute. The tag gets the value of the ServletContext attribute by using the applicationScope JSTL implicit object, which is a java.util.Map type. Example 16-6. Accessing an application attribute in a JSP<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> //HTML or other presentation code here... <c:out value= "${applicationScope[\"com.jspservletcookbook.ContextObject\"].values}" escapeXml="false" />
The code: ${applicationScope[\"com.jspservletcookbook.ContextObject\"].values} uses EL syntax to access the ServletContext attribute named com.jspservletcookbook.ContextObject and get its values property, which effectively calls the getValues( ) method on the ContextObject object. This method displays all the keys of the Map contained by ContextObject , separated by an HTML line break ( <br> ). The attribute escapeXml="false " prevents the < and > characters in <br> from being escaped (and being replaced by < and > , respectively), which would prevent its proper display in a web browser.
Figure 16-1 shows the result of accessing a JSP that uses this code in a browser. Figure 16-1. Accessing a ServletContext bound attribute in a JSPTo remove the attribute from the ServletContext , use the c:remove JSTL tag. This tag removes the named variable from the specified scope: <c:remove var= "com.jspservletcookbook.ContextObject" scope="application" /> application is an alias for the ServletContext . After a JSP that contains this tag is executed, any further attempts to access a ServletContext attribute of the same name will return null . See AlsoChapter 23 on using the JSTL; Recipe 16.1 and Recipe 16.2 on setting ServletContext attributes in servlets and JSPs; Recipe 16.3 on accessing or removing ServletContext attributes in servlets; Recipe 16.5-Recipe 16.8 on handling session attributes in servlets and JSPs; Recipe 16.9-Recipe 16.12 on handling request attributes in servlets and JSPs; Recipe 14.5 on using a ServletContext event listener; the Javadoc for javax.servlet.ServletContextAttributeListener : http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/ServletContextAttributeListener.html. |