6.2 The Config Class

   

The Config class, which resides in the javax.servlet.jsp.jstl. core package, defines the following static methods :

 Object find(PageContext pc, String name);  Object get(PageContext pc, String name, int scope); Object get(ServletRequest request, String name); Object get(HttpSession session, String name); Object get(ServletContext context, String name); void set(PageContext pc, String name, Object value,         int scope); void set(ServletRequest request, String name, Object value); void set(HttpSession session, String name, Object value); void set(ServletContext context, String name, Object value); void remove(PageContext pc, String name, int scope); void remove(ServletRequest request, String name); void remove(HttpSession session, String name); void remove(ServletContext context, String name); 

The find method searches all four scopes: page, request, session, and application, in that order, for a scoped variable with the specified name. When it finds a scoped variable, the search is over, and the method returns the scoped variable's value. If the method does not find a scoped variable, it returns the value of the context initialization parameter of the same name. If the method does not find a scoped variable and no context initialization parameter was specified, the method returns null .

The get , set , and remove methods let you manipulate configuration settings for various scopes from JSP pages, servlets, life-cycle listeners, servlet filters, and custom tags; for example, Config.set(PageContext, String name, Object value, int scope) lets you set a configuration setting, in a scope that you specify, from a JSP page or a custom action, whereas Config.set(HttpSession, String name, Object value) lets you set a configuration setting for a session. The latter method can be called from a servlet or life-cycle listener, whereas the former, which requires a page context, can only be called from a scriptlet or custom action because it requires a PageContext .

The Config class also defines a static constant for each of the configuration settings. Those constants are listed in Table 6.1 on page 234; how they are used is discussed in the rest of this chapter, which explores accessing configuration settings in servlets, life-cycle listeners, and custom actions.

Accessing Configuration Settings in Servlets

JSTL actions let you do lots of interesting things in JSP pages, but there's still a place for servlets in most JSP-based Web applications because servlets are excellent for encapsulating business and controller logic. Because of their utility and ubiquity, you may wish to access configuration settings from servlets, like the servlet listed in Listing 6.4.

The servlet listed in Listing 6.4 uses the Config class to set the FMT_LOCALE configuration setting for application scope when the servlet starts and rescinds that setting when the servlet is destroyed . That servlet is functionally equivalent to the deployment descriptor listed in Listing 6.1 on page 236; both the servlet and the deployment descriptor set the FMT_LOCALE configuration setting when their respective applications are loaded.

Listing 6.4 WEB-INF/classes/InitializationServlet.java
 import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.jstl.core.Config; public class InitializationServlet extends HttpServlet {    public void init() throws ServletException {  Config.  set(getServletContext(), Config.FMT_LOCALE, "fr");    }    public void destroy() {  Config.  remove(getServletContext(), Config.FMT_LOCALE);    } } 

Notice that the servlet listed in Listing 6.4 specifies a French locale with the string fr , but it could have specified that locale with an instance of java.util.Locale , like this:

 Config.set(getServletContext(), Config.FMT_LOCALE,  java.util.Locale.FRENCH  ); 

The servlet listed in Listing 6.4 must be loaded when the Web application is loaded, to ensure that the FMT_LOCALE configuration setting is in effect when the application runs. You specify that load-on-startup behavior in your deployment descriptor; for example, Listing 6.5 lists the deployment descriptor that declares the servlet listed in Listing 6.4.

The <load-on-startup> element specifies that the servlet must be loaded when the Web server starts.

Before we move on to life-cycle listeners, here's something to consider: Is the servlet discussed in this section equivalent to setting a context initialization parameter for the default locale, as we did in "Overview" on page 232?

The servlet discussed in this section is functionally equivalent to setting the FMT_LOCALE configuration setting in a deployment descriptor. Both approaches specify the FMT_LOCALE configuration setting for your application, and both can be temporarily overridden if you set the FMT_LOCALE configuration setting for page, request, or session scope. There is one small distinction, however. The servlet creates a configuration variable that's stored in application scope, whereas the deployment descriptor declares a context initialization parameter. The only practical difference between the two is that the configuration variable can be removed or replaced , whereas the context initialization parameter cannot, but the net effect is the same:

Listing 6.5 WEB-INF/web.xml
 <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app   PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"   "http://java.sun.com/j2ee/dtds/web-app_2.3.dtd"> <web-app>    <servlet>       <servlet-name>initServlet</servlet-name>       <servlet-class>InitializationServlet</servlet-class>  <load-on-startup/>  </servlet>    <welcome-file-list>       <welcome-file>page_1.jsp</welcome-file>    </welcome-file-list> </web-app> 

Config.find will find the configuration setting in both cases, as long as they have not been temporarily overridden in another scope. [4]

[4] See "Temporarily Overriding Configuration Settings" on page 235 for more information about overriding configuration settings.

Accessing Configuration Settings in Life-Cycle Listeners

You can also manipulate JSTL configuration settings with life-cycle listeners; for example, you might have a listener that sets the FMT_LOCALE configuration setting in accordance with a user's preferences whenever a session is activated for that user .

Listing 6.6 lists a simple life-cycle listener that is functionally equivalent to the servlet listed in Listing 6.4.

The preceding life-cycle listener is functionally equivalent to the deployment descriptor listed in Listing 6.1 on page 236 and the servlet listed in Listing 6.4; the listener, servlet, and deployment descriptor all set the FMT_LOCALE configuration setting in application scope when their respective applications are loaded.

Life-cycle listeners must be declared in a deployment descriptor. Listing 6.7 lists the deployment descriptor that declares the preceding life-cycle listener.

Because JSP containers use introspection on listener classes to discover the listener's type, you only have to declare a listener's class in your deployment descriptor. That type dictates when the listener's methods are invoked; for example, the listener listed in Listing 6.6 extends ServletContextListener , and therefore its contextInitialized and contextDestroyed methods are called when its servlet context is initialized and destroyed, respectively.

Listing 6.6 WEB-INF/classes/listeners/LocaleListener.java
 package listeners; import javax.servlet.*; import javax.servlet.jsp.jstl.core.Config; public class LocaleListener implements ServletContextListener {    public void contextInitialized(ServletContextEvent e) {  Config.set(e.getServletContext(), Config.FMT_LOCALE, "fr");  }    public void contextDestroyed(ServletContextEvent e) {  Config.remove(e.getServletContext(), Config.FMT_LOCALE);  } } 
Listing 6.7 WEB-INF/web.xml
 <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app   PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"   "http://java.sun.com/j2ee/dtds/web-app_2.3.dtd"> <web-app>    <listener>       <listener-class>  listeners.DataSourceListener  </listener-class>    </listener>    <welcome-file-list>       <welcome-file>page_1.jsp</welcome-file>    </welcome-file-list> </web-app> 

Accessing Configuration Settings in Custom Actions

This section rounds out our discussion of configuration settings by showing you how to access all of them in a custom action. Figure 6-3 shows a JSP page that uses that custom action.

Figure 6-3. Using a Custom Action That Prints Configuration Settings

graphics/06fig03.jpg

The JSP page shown in Figure 6-3 is listed in Listing 6.8.

Listing 6.8 index.jsp
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html>    <head>       <title>A Simple Use of JSTL I18N Actions</title>    </head>    <body>  <%@ taglib uri='WEB-INF/core-jstl.tld 'prefix='core-jstl'%>  <%@ taglib uri='http://java.sun.com/jstl/fmt' prefix='fmt'%>  <core-jstl:showConfigSettings/>  <fmt:setLocale value='en'/>       <fmt:setBundle basename='company'/>       <fmt:setTimeZone value='GMT'/>  <core-jstl:showConfigSettings/>  </body> </html> 

The preceding JSP page uses the custom action <core-jstl:showConfigSettings> to display all of the JSTL configuration settings, before and after setting the locale, bundle, and time zone configuration settings. Initially, the FMT_LOCALE and SQL_MAX_ROWS configuration settings are set to fr-CA and 28 , respectively, in the application's deployment descriptor. That deployment descriptor is listed in Listing 6.9.

Listing 6.9 WEB-INF/web.xml
 <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app   PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"   "http://java.sun.com/j2ee/dtds/web-app_2.3.dtd"> <web-app>    <context-param>       <param-name>  javax.servlet.jsp.jstl.fmt.locale  </param-name>       <param-value>  fr-CA  </param-value>    </context-param>    <context-param>       <param-name>  javax.servlet.jsp.jstl.sql.maxRows  </param-name>       <param-value>  28  </param-value>    </context-param>    <welcome-file-list>       <welcome-file>          index.jsp       </welcome-file>    </welcome-file-list> </web-app> 

The preceding deployment descriptor also specifies a welcome file. The Tag Library Descriptor (TLD) for the tag library is listed in Listing 6.10.

The preceding Tag Library Descriptor (TLD) specifies the tag library and its lone custom action. The tag handler for that custom action is listed in Listing 6.11.

Like the servlet and life-cycle listener discussed in Listing 6.4 on page 241 and Listing 6.6 on page 243, respectively, the tag handler listed above uses the Config class to access configuration settings. That tag handler prints all of the configuration settings, with special handling of the localization context setting, which specifies two things: a resource bundle and a locale. [5] Notice that the FMT_LOCALIZATION_CONTEXT configuration setting, like all JSTL configuration settings, can be specified with a string. [6] The tag handler listed in Listing 6.11 takes that possibility into account.

[5] See "Localization Contexts" on page 263 for more information about localization contexts.

[6] If you specify the FMT_LOCALIZATION_CONTEXT as a string, that string represents a resource bundle base name. See "Resource Bundles" on page 259 for more information about resource bundles.

Listing 6.10 WEB-INF/core-jstl.tld
 <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE taglib PUBLIC   "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"   "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_2.dtd"> <taglib>    <tlib-version>1.0</tlib-version>    <jsp-version>1.2</jsp-version>    <short-name>Core JSTL Example</short-name>    <description>       Show Configuration Settings with a Custom Action    </description>    <tag>       <name>showConfigSettings</name>       <tag-class>tags.ShowConfigSettingsTag</tag-class>       <body-content>empty</body-content>       <description>Shows configuration settings</description>    </tag> </taglib> 
Listing 6.11 WEB-INF/classes/tags/ShowConfigSettingsTag.java
 package tags; import java.io.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; import javax.servlet.http.*;  import javax.servlet.jsp.jstl.core.Config;   import javax.servlet.jsp.jstl.fmt.LocalizationContext;  public class ShowConfigSettingsTag extends TagSupport {    private static String[] settings = {       Config.FMT_LOCALE,              Config.FMT_FALLBACK_LOCALE,       Config.FMT_LOCALIZATION_CONTEXT,Config.FMT_TIME_ZONE,       Config.SQL_DATA_SOURCE,         Config.SQL_MAX_ROWS    };    public int doStartTag() throws JspException {       try {          JspWriter out = pageContext.getOut();          out.print("JSTL Configuration Settings:<p><ul>");          for(int i=0; i < settings.length; ++i) {             String name = settings[i];             Object o =  Config.find(pageContext, name);  out.print("<li><b>" + name + "</b>: ");             if(o == null)                out.print("null<br>");             else {                if(name.equals(Config.FMT_LOCALIZATION_CONTEXT)) {                   // Like all JSTL configuration settings, the                   // FMT_LOCALIZATION_CONTEXT setting can be                   // specified with a string...                   if(o instanceof java.lang.String)                      out.println(o);                   else {                      LocalizationContext lc =                                          (LocalizationContext)o;                      out.print("<ul><li>Resource Bundle: ");                      out.println(lc.getResourceBundle());                      out.print("<li>Locale: ");                      out.println(lc.getLocale() + "</ul>");                   }                }                else {                   out.print(o);                }             }          }          out.print("</ul></ul>");       }       catch(java.io.IOException ex) {          throw new JspException(ex.getMessage());       }       return SKIP_BODY;    } } 

In addition to illustrating how to access configuration settings from a custom action, you may also find the custom action discussed in this section useful as a debugging tool when you use the JSTL I18N, formatting, or SQL actions.

Now that you have a good understanding of JSTL configuration settings, you are ready to move on to the more advanced JSTL actions that let you internationalize your website, access a database, and use XML.

   


Core JSTL[c] Mastering the JSP Standard Tag Library
Core JSTL[c] Mastering the JSP Standard Tag Library
ISBN: 131001531
EAN: N/A
Year: 2005
Pages: 124

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net