Popular Posts

Saturday, May 30, 2009

The JSP include Directive

This directive lets you include files at the time the JSP page is translated into a servlet. The directive looks like this:

<%@ include file="relative url" %>

The URL specified is normally interpreted relative to the JSP page that refers to it, but, as with relative URLs in general, you can tell the system to interpret the URL relative to the home directory of the Web server by starting the URL with a forward slash. The contents of the included file are parsed as regular JSP text, and thus can include static HTML, scripting elements, directives, and actions.

For example, many sites include a small navigation bar on each page. Due to problems with HTML frames, this is usually implemented by way of a small table across the top of the page or down the left-hand side, with the HTML repeated for each page in the site. The include directive is a natural way of doing this, saving the developers from the maintenance nightmare of actually copying the HTML into each separate file. Here's some representative code:




Servlet Tutorial: JavaServer Pages (JSP) 1.0



HREF="Site-Styles.css"
TYPE="text/css">



<%@ include file="/navbar.html" %>






Note that since the include directive inserts the files at the time the page is translated, if the navigation bar changes, you need to re-translate all the JSP pages that refer to it. This is a good compromise in a situation like this, since the navigation bar probably changes infrequently, and you want the inclusion process to be as efficient as possible. If, however, the included files changed more often, you could use the jsp:include action instead. This includes the file at the time the JSP page is requested, and is discussed in the tutorial

No comments:

Post a Comment