Learn Java for Web Development

(Tina Meador) #1
CHAPTER 2: Building Web Applications Using Servlets and JSP 77

Include Directive


The include directive is used to specify static resources that should be included within the current
JSP page translation unit. The include directive has an attribute called file that specifies the URL
for the resource that should be included. The general form of this directive is as follows:


<%@ include file="relative url" >


The following example demonstrates using the include directive to include a standard JSP header
and footer in the current translation unit (Listing 2-15). You can create a project like your first web
application, helloworld, and replace helloworld.jsp with main.jsp. Listing 2-15 illustrates main.jsp.


Listing 2-15. main.jsp


1.<%@ include file="header.jsp" %>
2.
3.

content


4.
5.<%@ include file="footer.jsp" %>


   Line 1: This line includes header.jsp in the main.jsp file at translation time.
 Line 5: This line includes footer.jsp in the main.jsp file at translation time.

Listing 2-16 illustrates header.jsp.


Listing 2-16. header.jsp


1.
2.
3.
4.<%out.print("header"); %>


   Line 4: This line uses an implicit object out. Implicit objects will be introduced
later in this chapter. The implicit out object represents an instance of the
JspWriter class and is used to write character data to the response stream.

Listing 2-17 illustrates footer.jsp.


Listing 2-17. footer.jsp


1.<%out.print("footer"); %>
2.
3.


Figure 2-26 illustrates the output.

Free download pdf