How to include Other JSPs in Your JSP


Java™ 2 Primer Plus
By Steven Haines, Steve Potts

Table of Contents
Chapter 23.  Component-Based JavaServer Pages

How to include Other JSPs in Your JSP

One of the simplest forms of component software is the simple include. There are actually two different inclusion mechanisms that can be used in JSPs, the include directive and the include action.

The include Directive

The include directive can be used to insert the contents of another file into the JSP before the page is translated into a servlet. The JSP include is analogous to the #include that you find in C and C++ programs.

The syntax for this directive is very simple:

 <%@ include file="includes/heading.jsp" %> 

Listing 23.3 shows the include directive used in an example.

Listing 23.3 The IncludeDirectiveTest.jsp File
 <html>  <head>  <title>Include Directive Test</title>  <body>  <h2>Include Directive Test</h2>  This is the header  <%@ include file="includes/IncludeDirectiveHeader.jsp" %>  This is the body of the page.  <br>  This is the footer  <%@ include file="includes/IncludeDirectiveFooter.jsp" %>  </body>  </html> 

The include directive is expecting a URL that is relative to the location of the first JSP. It included the file in the exact location where the directive is found:

 <%@ include file="includes/IncludeDirectiveHeader.jsp" %> 

The contents of the two included files are very simple. The first one is shown in Listing 23.4.

Listing 23.4 The IncludeDirectiveHeader.jsp File
 <center>  <font size=10>  <b>  Include Directive Header  </b>  </font>  </center> 

The footer is very similar. It is shown in Listing 23.5.

Listing 23.5 The IncludeDirectiveFooter.jsp File
 <center>  <font size=10>  <b>  Include Directive Footer  </b>  </font>  </center> 

Both of these files must be stored in a directory called includes, which is a subdirectory of the current directory. Running this page generates the result shown in Figure 23.3.

Figure 23.3. The JSP include directive copies the contents of other files into this JSP before translation takes place.


Notice that a different font size was used for the header and footer so that they would stand out.


    Java 2 Primer Plus
    Java 2 Primer Plus
    ISBN: 0672324156
    EAN: 2147483647
    Year: 2001
    Pages: 332

    Similar book on Amazon © 2008-2017.
    If you may any questions please contact us: