Sun ONE logo      Previous      Contents      Index      Next     

Sun ONE Application Server 7 Developer's Guide to Web Applications

Chapter 3
Using JavaServer Pages

This chapter describes how to use JavaServer Pages (JSPs) as page templates in a Sun ONE Application Server web application.

This chapter contains the following sections:


Introducing JSPs

JSPs are browser pages in HTML or XML. They also contain Java code, which enables them to perform complex processing, conditionalize output, and communicate with other application objects. JSPs in Sun ONE Application Server are based on the JSP 1.2 specification. This specification is accessible from install_dir/docs/index.htm; install_dir is where the Sun ONE Application Server is installed.

In a Sun ONE Application Server application, JSPs are the individual pages that make up an application. You can call a JSP from a servlet to handle the user interaction output, or, since JSPs have the same application environment access as any other application component, you can use a JSP as an interaction destination.

JSPs are made up of JSP elements and template data. Template data is anything not in the JSP specification, including text and HTML tags. For example, the minimal JSP requires no processing by the JSP engine and is a static HTML page.

The Sun ONE Application Server compiles JSPs into HTTP servlets the first time they are called (or they can be precompiled for better performance). This makes them available to the application environment as standard objects and enables them to be called from a client using a URL.

JSPs run inside the server’s JSP engine, which is responsible for interpreting JSP specific tags and performing the actions they specify in order to generate dynamic content. This content, along with any template data surrounding it, is assembled into an output page and is returned to the caller.


Creating JSPs

You create JSPs in basically the same way you create HTML files. You can use an HTML editor to create pages and edit the page layout. You make a page a JSP by inserting JSP-specific tags into the raw source code where needed, and by giving the file a .jsp extension.

JSPs that adhere to the JSP 1.2 specification follow XML syntax for the most part, which is consistent with HTML. For a summary of the JSP tags you can use, see "JSP Tag Libraries and Standard Portable Tags".

JSPs are compiled into servlets, so servlet design considerations also apply to JSPs. JSPs and servlets can perform the same tasks, but each excels at one task at the expense of the other. Servlets are strong in processing and adaptability. However, performing HTML output from them involves many cumbersome println statements that must be coded by hand. Conversely, JSPs excel at layout tasks because they are simply HTML files and can be created with HTML editors, though performing complex computational or processing tasks with them is awkward. For information about servlets, see Chapter 2, "Using Servlets".

Here are a few additional JSP design tips:

Designing for Ease of Maintenance

Each JSP can call or include any other JSP. For example, you can create a generic corporate banner, a standard navigation bar, and a left-side column table of contents, where each element is in a separate JSP and is included for each page built. The page can be constructed with a JSP functioning as a frameset, dynamically determining the pages to load into each subframe. A JSP can also be included when the JSP is compiled into a servlet or when a request arrives.

Designing for Portability

JSPs can be completely portable between different applications and different servers. A disadvantage is that they have no particular application data knowledge, but this is only a problem if they require that kind of data.

One possible use for generic JSPs is for portable page elements, such as navigation bars or corporate headers and footers, which are meant to be included in other JSPs. You can create a library of reusable generic page elements to use throughout an application, or even among several applications.

For example, the minimal generic JSP is a static HTML page with no JSP-specific tags. A slightly less minimal JSP might contain some Java code that operates on generic data, such as printing the date and time, or that makes a change to the page’s structure based on a standard value set in the request object.

Handling Exceptions

If an uncaught exception occurs in a JSP file, Sun ONE Application Server generates an exception, usually a 404 or 500 error. To avoid this problem, set the errorPage attribute of the <%@ page%> tag.


JSP Tag Libraries and Standard Portable Tags

Sun ONE Application Server supports tag libraries and standard portable tags. For more information about tag libraries, see the JSP 1.2 specification at:

http://java.sun.com/products/jsp/download.html

For a handy summary of JSP 1.2 tag syntax, see the following PDF file:

http://java.sun.com/products/jsp/pdf/card12.pdf


JSP Caching

JSP caching lets you cache JSP page fragments within the Java engine. Each can be cached using different cache criteria. For example, suppose you have page fragments to view stock quotes, weather information, and so on. The stock quote fragment can be cached for 10 minutes, the weather report fragment for 30 minutes, and so on.

For more information about response caching as it pertains to servlets, see "Caching Servlet Results".

JSP caching uses the custom tag library support provided by JSP 1.2. JSP caching is implemented by a tag library packaged into the install_dir/lib/appserv-tags.jar file, which you can copy into the WEB-INF/lib directory of your web application. The appserv-tags.tld tag description file is in this JAR file and in the install_dir/lib/tlds directory.

You refer to these tags in your JSP files as follows:

<%@ taglib prefix="prefix" uri="Sun ONE Application Server Tags" %>

Subsequently, the cache tags are available as <prefix:cache> and <prefix:flush>. For example, if your prefix is mypfx, the cache tags are available as <mypfx:cache> and <mypfx:flush>.

If you wish to use a different URI for this tag library, you can use an explicit <taglib> element in your web.xml file.

The tags are as follows:

cache

The cache tag caches the body between the beginning and ending tags according to the attributes specified. The first time the tag is encountered, the body content is executed and cached. Each subsequent time it is run, the cached content is checked to see if it needs to be refreshed and if so, it is executed again, and the cached data is refreshed. Otherwise, the cached data is served.

Attributes

The following table describes attributes for the cache tag. The left column lists the attribute name, the middle column indicates the default value, and the right column describes what the attribute does.

Table 3-1  cache attributes

Attribute

Default

Description

key

ServletPath_Suffix

(optional) The name used by the container to access the cached entry. The cache key is suffixed to the servlet path to generate a key to access the cached entry. If no key is specified, a number is generated according to the position of the tag in the page.

timeout

60s

(optional) The time in seconds after which the body of the tag is executed and the cache is refreshed. By default, this value is interpreted in seconds. To specify a different unit of time, add a suffix to the timeout value as follows: s for seconds, m for minutes, h for hours, d for days. For example, 2h specifies two hours.

nocache

false

(optional) If set to true, the body content is executed and served as if there were no cache tag. This offers a way to programmatically decide whether the cached response should be sent or whether the body has to be executed, though the response is not cached.

refresh

false

(optional) If set to true, the body content is executed and the response is cached again. This lets you programmatically refresh the cache immediately regardless of the timeout setting.

Example

The following example represents a cached JSP page:

<%@ taglib prefix="mypfx" uri="Sun ONE Application Server Tags" %>

<%
  String cacheKey = null;
  if (session != null)
    cacheKey = (String)session.getAttribute("loginId");

  // check for nocache
  boolean noCache = false;
  String nc = request.getParameter("nocache");
  if (nc != null)
    noCache = "true";

  // force reload
  boolean reload=false;
  String refresh = request.getParameter("refresh");
  if (refresh != null)
    reload = true;
%>

<mypfx:cache key="<%= cacheKey %>" nocache="<%= noCache %>" refresh="<%= reload %>" timeout="10m">
<%
  String page = request.getParameter("page");
  if (page.equals("frontPage") {
    // get headlines from database
  } else {
    .....
%>
</mypfx:cache>

<mypfx:cache timeout="1h">
<h2> Local News </h2>
<%
  // get the headline news and cache them
%>
</mypfx:cache>

flush

Forces the cache to be flushed. If a key is specified, only the entry with that key is flushed. If no key is specified, the entire cache is flushed.

Attributes

The following table describes attributes for the flush tag. The left column lists the attribute name, the middle column indicates the default value, and the right column describes what the attribute does.

Table 3-2  flush attributes

Attribute

Default

Description

key

ServletPath_Suffix

(optional) The name used by the container to access the cached entry. The cache key is suffixed to the servlet path to generate a key to access the cached entry. If no key is specified, a number is generated according to the position of the tag in the page.

Examples

To flush the entry with key="foobar":

<mypfx:flush key="foobar"/>

To flush the entire cache:

<% if (session != null && session.getAttribute("clearCache") != null) { %>
    <mypfx:flush />
<% } %>


Compiling JSPs: The Command-Line Compiler

Sun ONE Application Server provides the following ways of compiling JSP 1.2 compliant source files into servlets:

To allow the JSP container to pick up the precompiled JSPs from a JAR file, you must disable dynamic reloading of JSPs. To do this, set the reload-interval property to -1 in the jsp-config element of the sun-web.xml file. See "JSP Elements".

The jspc command line tool is located under install_dir/bin (make sure this directory is in your path). The format of the jspc command is as follows:

jspc [options] file_specifier

The following table shows what file_specifier can be in the jspc command. The left column lists file specifiers, and the right column lists descriptions of those file specifiers.

Table 3-3  File specifiers for the jspc command

File Specifier

Description

files

One or more JSP files to be compiled.

-webapp dir

A directory containing a web application. All JSPs in the directory and its subdirectories are compiled. You cannot specify a WAR, JAR, or ZIP file; you must first extract it to an open directory structure.

The following table shows the basic options for the jspc command. The left column lists options, and the right column lists descriptions of those options.

Table 3-4  Basic jspc options

Option

Description

-q

Enables quiet mode (same as -v0). Only fatal error messages are displayed.

-d dir

Specifies the output directory for the compiled JSPs. Package directories are automatically generated based on the directories containing the uncompiled JSPs. The default top-level directory is the directory from which jspc is invoked.

-p name

Specifies the name of the target package for all specified JSPs, overriding the default package generation performed by the -d option.

-c name

Specifies the target class name of the first JSP compiled. Subsequent JSPs are unaffected.

-uribase dir

Specifies the URI directory to which compilations are relative. Applies only to JSP files listed in the command, and not to JSP files specified with -webapp.

This is the location of each JSP file relative to the uriroot. If this cannot be determined, the default is /.

-uriroot dir

Specifies the root directory against which URI files are resolved. Applies only to JSP files listed in the command, and not to JSP files specified with -webapp.

If this option is not specified, all parent directories of the first JSP page are searched for a WEB-INF subdirectory. The closest directory to the JSP page that has one is used.

If none of the JSP’s parent directories have a WEB-INF subdirectory, the directory from which jspc is invoked is used.

-genclass

Compiles the generated servlets into class files.

The following table shows the advanced options for the jspc command. The left column lists options, and the right column lists descriptions of those options.

Table 3-5  Advanced jspc options

Option

Description

-v[level]

Enables verbose mode. The level is optional; the default is 2. Possible level values are:

  • 0 - fatal error messages only
  • 1 - error messages only
  • 2 - error and warning messages only
  • 3 - error, warning, and informational messages
  • 4 - error, warning, informational, and debugging messages

-mapped

Generates separate write calls for each HTML line and comments that describe the location of each line in the JSP file. By default, all adjacent write calls are combined and no location comments are generated.

-die[code]

Returns the error number specified by code if an error occurs. If the code is absent or unparsable it defaults to 1.

-webinc file

Creates partial servlet mappings for the -webapp option, which can be pasted into a web.xml file.

-webxml file

Creates an entire web.xml file for the -webapp option.

-ieplugin class_id

Specifies the Java plugin COM class ID for Internet Explorer. Used by the <jsp:plugin> tags.

For example, this command compiles the hello JSP file and writes the compiled JSP under hellodir:

jspc -d hellodir -genclass hello.jsp

This command compiles all the JSP files in the web application under webappdir into class files under jspclassdir:

jspc -d jspclassdir -genclass -webapp webappdir

To use either of these precompiled JSPs in a web application, put the classes under hellodir or jspclassdir into a JAR file, place the JAR file under WEB-INF/lib, and set the reload-interval property to -1 in the sun-web.xml file.


Debugging JSPs

When you use Sun ONE Studio 4 to debug JSPs, you can set breakpoints in either the JSP code or the generated servlet code, and you can switch between them and see the same breakpoints in both.

To set up debugging in Sun ONE Studio, see the Sun ONE Application Server Developer’s Guide. For further details, see the Sun ONE Studio 4, Enterprise Edition Tutorial.



Previous      Contents      Index      Next     


Copyright 2003 Sun Microsystems, Inc. All rights reserved.