3.5. Including Files and Applets in JSP Documents

JSP has three main capabilities for including external pieces into a JSP document.

  1. The include directive. The construct lets you insert JSP code into the main page before that main page is translated into a servlet. The included code can contain JSP constructs such as field definitions and content-type settings that affect the main page as a whole. This capability is discussed in the first of the following subsections.

  2. The jsp:include action. Although reusing chunks of JSP code is a powerful capability, most times you would rather sacrifice a small amount of power for the convenience of being able to change the included documents without updating the main JSP page. The jsp:include action lets you include the output of a page at request time. Note that jsp:include only lets you include the output of the secondary page, not the secondary page’s actual code as with the include directive. Consequently, the secondary page cannot use any JSP constructs that affect the main page as a whole. Use of jsp:include is discussed in the second subsection.

  3. The jsp:plugin action. Although this chapter is primarily about server-side Java, client-side Java in the form of Web-embedded applets continues to play a role, especially within corporate intranets. The jsp:plugin element is used to insert applets that use the Java Plug-In into JSP pages. This capability is discussed in the third subsection.

Including Files at Page Translation Time: The include Directive

You use the include directive to include a file in the main JSP document at the time the document is translated into a servlet (which is typically the first time it is accessed). The syntax is as follows:

<%@ include file="Relative URL" %> 

There are two ramifications of the fact that the included file is inserted at page translation time, not at request time as with jsp:include (see the next subsection).

First, the included file is permitted to contain JSP code such as response header settings and field definitions that affect the main page. For example, suppose snippet.jsp contained the following code:

<%! int accessCount = 0; %> 

In such a case, you could do the following:

<%@ include file="snippet.jsp" %> <%-- Defines accessCount --%> 
<%= accessCount++ %>              <%-- Uses accessCount --%> 

Second, if the included file changes, all the JSP files that use it may need to be updated. Unfortunately, although servers are allowed to support a mechanism for detecting when an included file has changed (and then recompiling the servlet), they are not required to do so. So, you may have to update the modification dates of each JSP page that uses the included code. Some operating systems have commands that update the modification date without your actually editing the file (e.g., the Unix touch command), but a simple portable alternative is to include a JSP comment in the top-level page. Update the comment whenever the included file changes. For example, you might put the modification date of the included file in the comment, as below.

<%-- Navbar.jsp modified 3/1/00 --%> 
<%@ include file="Navbar.jsp" %> 

Core Warning

If you change an included JSP file, you may have to update the modification dates of all JSP files that use it.


XML Syntax for the include Directive

The XML-compatible equivalent of

<%@ include file="..." %> 

is

<jsp:directive.include file="..." /> 

Remember that only servlet and JSP containers (servers) that support JSP 1.2 are required to support the XML version.

Including Pages at Request Time: The jsp:include Action

The include directive (see the previous subsection) lets you include actual JSP code into multiple different pages. Including the code itself is sometimes a useful capability, but the include directive requires you to update the modification date of the page whenever the included file changes. This is a significant inconvenience. The jsp:include action includes the output of a secondary page at the time the main page is requested. Thus, jsp:include does not require you to update the main file when an included file changes. On the other hand, the main page has already been translated into a servlet by request time, so the included pages cannot contain JSP that affects the main page as a whole. Also, inclusion at page translation time is marginally faster. These are relatively minor considerations, and jsp:include is almost always preferred.

Core Approach

For file inclusion, use jsp:include whenever possible. Reserve the include directive for cases when the included file defines fields or methods that the main page uses or when the included file sets response headers of the main page.


Although the output of the included pages cannot contain JSP, the pages can be the result of resources that use JSP to create the output. That is, the URL that refers to the included resource is interpreted in the normal manner by the server and thus can be a servlet or JSP page. The server runs the included page in the usual manner and places the output into the main page. This is precisely the behavior of the include method of the RequestDispatcher class (Section 3.8), which is what servlets use if they want to do this type of file inclusion.

The jsp:include element has two attributes, as shown in the sample below: page and flush. The page attribute is required and designates a relative URL referencing the file to be included. The flush attribute specifies whether the output stream of the main page should flushed before the inclusion of the page. In JSP 1.2, flush is an optional attribute and the default value is false. In JSP 1.1, flush is a required attribute and the only legal value is true.

<jsp:include page="Relative URL" flush="true" /> 

The included file automatically is given the same request parameters as the originally requested page. If you want to augment those parameters, you can use the jsp:param element (which has name and value attributes). For example, consider the following snippet.

<jsp:include page="/fragments/StandardHeading.jsp"> 
  <jsp:param name="bgColor" value="YELLOW" /> 
</jsp:include> 

Now, suppose that the main page is invoked by means of http://host/path/MainPage.jsp?fgColor=RED. In such a case, the main page receives "RED" for calls to request.getParameter("fgColor") and null for calls to request.getParameter("bgColor") (regardless of whether the bgColor attribute is accessed before or after the inclusion of the StandardHeading.jsp page). The StandardHeading.jsp page would receive "RED" for calls to request.getParameter("fgColor") and "YELLOW" for calls to request.getParameter("bgColor"). If the main page receives a request parameter that is also specified with the jsp:param element, the value from jsp:param takes precedence in the included page.

As an example of a typical use of jsp:include, consider the simple news summary page shown in Listing 3.12. Page developers can change the news items in the files Item1.html through Item3.html (Listings 3.13 through 3.15) without having to update the main news page. Figure 3-12 shows the result.

Figure 3-12. Including files at request time makes it easier to update the individual files.


Listing 3.12. WhatsNew.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 
<HTML> 
<HEAD> 
<TITLE>What's New at JspNews.com</TITLE> 
<LINK REL=STYLESHEET 
      HREF="JSP-Styles.css" 
      TYPE="text/css"> 
</HEAD> 
<BODY> 
<TABLE BORDER=5 ALIGN="CENTER"> 
  <TR><TH CLASS="TITLE"> 
      What's New at JspNews.com</TABLE> 
<P> 
Here is a summary of our three most recent news stories: 
<OL> 
  <LI><jsp:include page="news/Item1.html" flush="true" /> 
  <LI><jsp:include page="news/Item2.html" flush="true" /> 
  <LI><jsp:include page="news/Item3.html" flush="true" /> 
</OL> 
</BODY> 
</HTML> 

Listing 3.13. Item1.html
<B>Bill Gates acts humble.</B> In a startling and unexpected 
development, Microsoft big wig Bill Gates put on an open act of 
humility yesterday. 
<A HREF="http://www.microsoft.com/Never.html">More details...</A> 

Listing 3.14. Item2.html
<B>Scott McNealy acts serious.</B> In an unexpected twist, 
wisecracking Sun head Scott McNealy was sober and subdued at 
yesterday's meeting. 
<A HREF="http://www.sun.com/Imposter.html">More details...</A> 

Listing 3.15. Item3.html
<B>Larry Ellison acts conciliatory.</B> Catching his competitors 
off guard yesterday, Oracle prez Larry Ellison referred to his 
rivals in friendly and respectful terms. 
<A HREF="http://www.oracle.com/Mistake.html">More details...</A> 

Including Applets for the Java Plug-In

With JSP, you don’t need any special syntax to include ordinary applets: just use the normal HTML APPLET tag. However, except for intranets that use Netscape 6 exclusively, these applets must use JDK 1.1 or JDK 1.02 since neither Netscape 4.x nor Internet Explorer 5.x supports the Java 2 platform (i.e., JDK 1.2–1.4). This lack of support imposes several restrictions on applets:

To use Swing, you must send the Swing files over the network. This process is time consuming and fails in Internet Explorer 3 and Netscape 3.x and 4.01–4.05 (which only support JDK 1.02), since Swing depends on JDK 1.1.

You cannot use Java 2D.

You cannot use the Java 2 collections package.

Your code runs more slowly, since most compilers for the Java 2 platform are significantly improved over their 1.1 predecessors.

To address these problems, Sun developed a browser plug-in for Netscape and Internet Explorer that lets you use the Java 2 platform in a variety of browsers. This plug-in is available at http://java.sun.com/products/plugin/ and also comes bundled with JDK 1.2.2 and later. Since the plug-in is quite large (several megabytes), it is not reasonable to expect users on the WWW at large to download and install it just to run your applets. On the other hand, it is a reasonable alternative for fast corporate intranets, especially since applets can automatically prompt browsers that lack the plug-in to download it.

Unfortunately, however, the normal APPLET tag will not work with the plug-in, since browsers are specifically designed to use only their built-in virtual machine when they see APPLET. Instead, you have to use a long and messy OBJECT tag for Internet Explorer and an equally long EMBED tag for Netscape. Furthermore, since you typically don’t know which browser type will be accessing your page, you have to either include both OBJECT and EMBED (placing the EMBED within the COMMENT section of OBJECT) or identify the browser type at the time of the request and conditionally build the right tag. This process is straightforward but tedious and time consuming.

The jsp:plugin element instructs the server to build a tag appropriate for applets that use the plug-in. This element does not add any Java capabilities to the client. How could it? JSP runs entirely on the server; the client knows nothing about JSP. The jsp:plugin element merely simplifies the generation of the OBJECT or EMBED tags.

Servers are permitted some leeway in exactly how they implement jsp:plugin but most simply include both OBJECT and EMBED. To see exactly how your server translates jsp:plugin, insert into a page a simple jsp:plugin element with type, code, width, and height attributes as in the following example. Then, access the page from your browser and view the HTML source. You don’t need to create an applet to perform this experiment.

Note that JRun 3.0 SP2 does not support jsp:plugin; JRun 3.1 supports it properly.

The jsp:plugin Element

The simplest way to use jsp:plugin is to supply four attributes: type, code, width, and height. You supply a value of applet for the type attribute and use the other three attributes in exactly the same way as with the APPLET element, with two exceptions: the attribute names are case sensitive, and single or double quotes are always required around the attribute values. So, for example, you could replace

<APPLET CODE="MyApplet.class" 
        WIDTH=475 HEIGHT=350> 
</APPLET> 

with

<jsp:plugin type="applet" 
            code="MyApplet.class" 
            width="475" height="350"> 
</jsp:plugin> 

The jsp:plugin element has a number of other optional attributes. Most parallel the attributes of the APPLET element. Here is a full list.

  • type For applets, this attribute should have a value of applet. However, the Java Plug-In also permits you to embed JavaBeans components in Web pages. Use a value of bean in such a case.

  • code This attribute is used identically to the CODE attribute of APPLET, specifying the top-level applet class file that extends Applet or JApplet.

  • width This attribute is used identically to the WIDTH attribute of APPLET, specifying the width in pixels to be reserved for the applet.

  • height This attribute is used identically to the HEIGHT attribute of APPLET, specifying the height in pixels to be reserved for the applet.

  • codebase This attribute is used identically to the CODEBASE attribute of APPLET, specifying the base directory for the applets. The code attribute is interpreted relative to this directory. As with the APPLET element, if you omit this attribute, the directory of the current page is used as the default. In the case of JSP, this default location is the directory where the original JSP file resided, not the system-specific location of the servlet that results from the JSP file.

  • align This attribute is used identically to the ALIGN attribute of APPLET and IMG, specifying the alignment of the applet within the Web page. Legal values are left, right, top, bottom, and middle.

  • hspace This attribute is used identically to the HSPACE attribute of APPLET, specifying empty space in pixels reserved on the left and right of the applet.

  • vspace This attribute is used identically to the VSPACE attribute of APPLET, specifying empty space in pixels reserved on the top and bottom of the applet.

  • archive This attribute is used identically to the ARCHIVE attribute of APPLET, specifying a JAR file from which classes and images should be loaded.

  • name This attribute is used identically to the NAME attribute of APPLET, specifying a name to use for interapplet communication or for identifying the applet to scripting languages like JavaScript.

  • title This attribute is used identically to the very rarely used TITLE attribute of APPLET (and virtually all other HTML elements in HTML 4.0), specifying a title that could be used for a tool-tip or for indexing.

  • jreversion This attribute identifies the version of the Java Runtime Environment (JRE) that is required. The default is 1.1.

  • iepluginurl This attribute designates a URL from which the plug-in for Internet Explorer can be downloaded. Users who don’t already have the plug-in installed will be prompted to download it from this location. The default value will direct the user to the Sun site, but for intranet use you might want to direct the user to a local copy.

  • nspluginurl This attribute designates a URL from which the plug-in for Netscape can be downloaded. The default value will direct the user to the Sun site, but for intranet use you might want to direct the user to a local copy.

The jsp:param and jsp:params Elements

The jsp:param element is used with jsp:plugin in a manner similar to the way that PARAM is used with APPLET, specifying a name and value that are accessed from within the applet by getParameter. There are two main differences, however. First, since jsp:param follows XML syntax, attribute names must be lower case, attribute values must be enclosed in single or double quotes, and the element must end with />, not just >. Second, all jsp:param entries must be enclosed within a jsp:params element.

So, for example, you would replace

<APPLET CODE="MyApplet.class" 
        WIDTH=475 HEIGHT=350> 
  <PARAM NAME="PARAM1" VALUE="VALUE1">
								<PARAM NAME="PARAM2" VALUE="VALUE2"> 
</APPLET> 

with

<jsp:plugin type="applet" 
            code="MyApplet.class" 
            width="475" height="350"> 
  <jsp:params>
								<jsp:param name="PARAM1" value="VALUE1" />
								<jsp:param name="PARAM2" value="VALUE2" />
								</jsp:params> 
</jsp:plugin> 

The jsp:fallback Element

The jsp:fallback element provides alternative text to browsers that do not support OBJECT or EMBED. You use this element in almost the same way as you would use alternative text placed within an APPLET element. So, for example, you would replace

<APPLET CODE="MyApplet.class" 
        WIDTH=475 HEIGHT=350> 
  <B>Error: this example requires Java.</B> 
</APPLET> 

with

<jsp:plugin type="applet" 
            code="MyApplet.class" 
            width="475" height="350"> 
  <jsp:fallback>
								<B>Error: this example requires Java.</B>
								</jsp:fallback> 
</jsp:plugin> 

A jsp:plugin Example

Listing 3.16 shows a JSP page that uses the jsp:plugin element to generate an entry for the Java 2 Plug-In. Listings 3.17 through 3.20 show the code for the applet itself (which uses Swing and Java 2D), and Figure 3-13 shows the result.

Figure 3-13. Result of PluginApplet.jsp in Internet Explorer when the Java 2 Plug-In is installed.


Listing 3.16. PluginApplet.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 
<HTML> 
<HEAD> 
<TITLE>Using jsp:plugin</TITLE> 
<LINK REL=STYLESHEET 
      HREF="JSP-Styles.css" 
      TYPE="text/css"> 
</HEAD> 
<BODY> 
<TABLE BORDER=5 ALIGN="CENTER"> 
  <TR><TH CLASS="TITLE"> 
      Using jsp:plugin</TABLE> 
<P> 
<CENTER> 
<jsp:plugin type="applet"
								code="PluginApplet.class"
								width="370" height="420">
								</jsp:plugin> 
</CENTER> 
</BODY> 
</HTML> 

Listing 3.17. PluginApplet.java
import javax.swing.*; 

/** An applet that uses Swing and Java 2D and thus requires 
 *  the Java Plug-In. 
 */ 

public class PluginApplet extends JApplet {
  public void init() {
    WindowUtilities.setNativeLookAndFeel(); 
    setContentPane(new TextPanel()); 
  } 
} 

Listing 3.18. TextPanel.java
import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 

/** JPanel that places a panel with text drawn at various angles 
 *  in the top part of the window and a JComboBox containing 
 *  font choices in the bottom part. 
 */ 

public class TextPanel extends JPanel 
                       implements ActionListener {
  private JComboBox fontBox; 
  private DrawingPanel drawingPanel; 

  public TextPanel() {
    GraphicsEnvironment env = 
      GraphicsEnvironment.getLocalGraphicsEnvironment(); 
    String[] fontNames = env.getAvailableFontFamilyNames(); 
    fontBox = new JComboBox(fontNames); 
    setLayout(new BorderLayout()); 
    JPanel fontPanel = new JPanel(); 
    fontPanel.add(new JLabel("Font:")); 
    fontPanel.add(fontBox); 
    JButton drawButton = new JButton("Draw"); 
    drawButton.addActionListener(this); 
    fontPanel.add(drawButton); 
    add(fontPanel, BorderLayout.SOUTH); 
    drawingPanel = new DrawingPanel(); 
    fontBox.setSelectedItem("Serif"); 
    drawingPanel.setFontName("Serif"); 
    add(drawingPanel, BorderLayout.CENTER); 
  } 

  public void actionPerformed(ActionEvent e) {
    drawingPanel.setFontName((String)fontBox.getSelectedItem()); 
    drawingPanel.repaint(); 
  } 
} 

Listing 3.19. DrawingPanel.java
import java.awt.*; 
import java.awt.geom.*; 
import javax.swing.*; 

/** A window with text drawn at an angle. The font is 
 *  set by means of the setFontName method. 
 */ 

class DrawingPanel extends JPanel {
  private Ellipse2D.Double circle = 
    new Ellipse2D.Double(10, 10, 350, 350); 
  private GradientPaint gradient = 
    new GradientPaint(0, 0, Color.red, 180, 180, Color.yellow, 
                      true); // true means to repeat pattern 
  private Color[] colors = { Color.white, Color.black }; 

  public void paintComponent(Graphics g) {
    super.paintComponent(g); 
    Graphics2D g2d = (Graphics2D)g; 
    g2d.setPaint(gradient); 
    g2d.fill(circle); 
    g2d.translate(185, 185); 
    for (int i=0; i<16; i++) {
      g2d.rotate(Math.PI/8.0); 
      g2d.setPaint(colors[i%2]); 
      g2d.drawString("jsp:plugin", 0, 0); 
    } 
  } 

  public void setFontName(String fontName) {
    setFont(new Font(fontName, Font.BOLD, 35)); 
  } 
} 

Listing 3.20. WindowUtilities.java
import javax.swing.*; 
import java.awt.*; 

/** A few utilities that simplify using windows in Swing. */ 

public class WindowUtilities {

  /** Tell system to use native look and feel, as in previous 
   *  releases. Metal (Java) LAF is the default otherwise. 
   */ 

  public static void setNativeLookAndFeel() {
    try {
      UIManager.setLookAndFeel 
        (UIManager.getSystemLookAndFeelClassName()); 
    } catch(Exception e) {
      System.out.println("Error setting native LAF: " + e); 
    } 
  } 

  ... // See www.moreservlets.com for remaining code. 
} 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.176.5