Page #473 (Programming Exercises)
Chapter 35. JavaServer Pages
Mayan God Shel, Mexico. Photographer: Philip Coblentz. Courtesy Brand X Pictures.
Servlets can be used to generate dynamic Web content. One drawback, however, is that you have to embed HTML tags and text inside the Java source code. Using servlets, you have to modify the Java source code and recompile it if changes are made to the HTML text. If you have a lot of HTML script in a servlet, the program is difficult to read and maintain, since the HTML text is part of the Java program. JavaServer Pages (JSP) technology was introduced to remedy this drawback. JSP enables you to write regular HTML script in the normal way and embed Java code to produce dynamic content.
[Page 1210 (
35.2. A Simple JSP Page
JSP provides an easy way to create dynamic Web pages and simplify the task of building Web applications. A JavaServer page is like a regular HTML page with special tags, known as
, which enable the Web server to generate dynamic content. You can create a Web page with HTML script and enclose the Java code for generating dynamic content in the JSP tags. Here is an example of a simple JSP page.
<! CurrentTime.jsp >
Current time is
The dynamic content is
in the tag that begins with
and ends with
. The current time is returned as a string by invoking the
method of an object of the
To display the JSP page, you need to create a text file for the page,
the file CurrentTime.jsp, and store the file in
. Assume you have started Tomcat. You can run it from a Web browser using the URL
, as shown in Figure 35.1.
Figure 35.1. A JSP page is displayed in a Web browser.
You created the context root directory
under the Tomcat webapps directory in the
way to run JSP for new JSP programmers is to store all the JSP files in
. You can also place JSP files elsewhere. For more information, see Supplement VII.E, "
35.3. How Is a JSP Page
A JSP page must first be processed by a Web server before it can be displayed in a Web browser. The Web server must support JSP, and the JSP page must be stored in a file with a .jsp extension. The Web server
the .jsp file into a Java servlet, compiles the servlet, and executes it. The result of the execution is sent to the browser for display. Figure 35.2 shows how a JSP page is processed by a Web server. CurrentTime.jsp in Figure 35.1 is translated into a servlet named CurrentTime_jsp.java in
. Viewing the file will help you to better understand that JSP is based on the servlet.
Figure 35.2. A JSP page is translated into a servlet.
A JSP page is translated into a servlet when the page is
for the first time. It is not retranslated if the page is not modified. To ensure that the first-time real
does not get a delay, JSP developers may test the page after it is installed.