HTML Meets Java: JSP

Problem

You have a web page that could use a jolt of Java.

Solution

Use the JavaServer Pages method of mixing HTML and Java.

Discussion

JavaServer Pages (JSP) shares some general syntax with Microsoft’s ASP (Application Server Pages) and the free-software PHP (Programmable Hypertext Processor). They allow a mix of HTML and code; the code is executed on the server side, and the HTML plus the code results are printed as HTML. Because of Java’s portability and JSP’s full access to the entire Java API, JSP may be the most exciting web technology to come along since the online pizza demonstration. Example 18-11, for example, is the “five integers” code as a JSP.

Example 18-11.  fiveints.jsp

<HTML>
<HEAD>
<TITLE>Your Personal Random Numbers</TITLE>
<H1>Your Personal Random Numbers</H1>
<P>Here are your personal random numbers,
carefully selected by a
<A HREF=\"http://java.sun.com\">Java</A> program.
<OL>
    <%
    java.util.Random r = new java.util.Random(  );
    for (int i=0; i<5; i++) {
        out.print("<LI>");
        out.println(r.nextInt(  ));
    }
    %>
</OL>
<HR></HR>
<A HREF=\"index.html\">Back to main Page</A>

Notice how much more compact this is than the servlet version in Section 18.2. It should not surprise you to learn that JSPs are actually compiled into servlets, so most of what you know about servlets also applies to JSP. Let’s look at another example that generates an HTML form and calls itself back when you activate the form, and also contains an HTML table to display the current ...

Get Java Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.