[ Team LiB ] 2.3 Including Text in

[ Team LiB ] 2.3 Including Text in a JSP Removing 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 Hello again, world! 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 content This 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. Errors to Watch For Includes can suffer from the same kinds of errors as comments. First, tags can be broken, such as , which is missing the closing slash. The JSP engine will catch this error and report it as /index.jsp(3,0) Expected “param” tag with “name” and”value” attributes without the “params” tag. It is also possible to attempt to include a file that does not exist, which will usually happen because of a typo, such as typing headers.jsp instead of header.jsp. In this case, the JSP engine will report “Can’t read file headers.jsp,” which is easily fixed. 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 Page 26

Hint: This post is supported by Gama web hosting hrvatska services

Comments are closed.