| [ directory ] |
|
2.3 Including Text in a JSPRemoving text from a page is only slightly useful; it is much more exciting to consider ways in which a JSP can add data to a page. This data may come from any number of places, such as a database, some Java code, or data explicitly provided by the user. Regardless of the source, it will be the JSP's job to inject this data into the page. The first and simplest place a JSP can get data from is another JSP. Listing 2.2 shows a slightly modified version of Listing 2.1. Listing 2.2 A JSP that includes another JSP<html> <body> Hello again, world! <jsp:include page="content.jsp"/> </body> </html> This turns into a program just as Listing 2.1 did, and once again, all the HTML tags turn into instructions that send those tags to the browser. The jsp:include tag turns into an instruction for the JSP engine to run the program called content.jsp, which is shown in Listing 2.3. Listing 2.3 The included contentThis is some text from content.jsp. Note that Listing 2.3 contains a complete and valid JSP. A browser could request content.jsp directly, and the response would be the message with no HTML or other tags. However, the intended use is that the browser will request the top-level page, which will render its content, and then the jsp:include tag will call content.jsp. Control will then return to the original page, which will send the final closing body and HTML tags. The result, as far as the browser is concerned, will look exactly as if all the HTML was in the original page all along.
Two files do not make for a very interesting site, but the jsp:include tag becomes much more useful when there are many more files. In one common scenario, many files may all want to include some common text. For example, every page on a site might have at the bottom a clever or amusing quote that the site administrators change once a week. If this quote is kept in its own JSP, it is necessary to change only that one file in order to change the whole site. Conversely, one file may want to include several others. A customized news site might have separate JSPs for top headlines, technology stories, weather, and sports. Many different combinations of content pages could then be easily created by simply choosing which of these pieces to include. In this sense, using JSPs is a lot like building with LEGOS: Whole sites can be constructed by combining simple blocks in different ways. Both of these techniques will be used extensively later in this chapter. Closely related to the jsp:include tag is another, called jsp:forward. Whereas jsp:include includes the contents of one page within another, jsp:forward simply sends the user to another page. This requires that the page issuing the jsp:forward have no text other than blank lines either before or after the tag. This may not seem useful yet but later will allow pages to make decisions about what content should be displayed. |
| [ directory ] |
|