ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.

advertisement

AddThis Social Bookmark Button

Web Server Java -- Servlets and JSP
Pages: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11

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</h2>
<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 First Servlet: Generating an HTML Page. 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 month. Figure 18-9 and Example 18-12 show a JSP version of the CalendarPage program.

Screen shot.
Figure 18-9. CalendarPage.jsp in action.


Example 18-12: CalendarPage.jsp

<%@page import="java.util.*,java.text.*" %>
 
<head>
  <title>Print a month page.</title>
  <meta name="version"
</head>
<body bgcolor="white">
<h1>Print a month page, for the Western calendar.</h2>
<P>Author Ian F. Darwin, ian@darwinsys.com
 
<%  // First get the month and year from the form.
  boolean yyok = false;  // -1 is a valid year, use boolean
  int yy = 0, mm = 0;
  String yyString = request.getParameter("year");
  if (yyString != null && yyString.length(  ) > 0) {
    try {
      yy = Integer.parseInt(yyString);
      yyok = true;
    } catch (NumberFormatException e) {
      out.println("Year " + yyString + " invalid");
    }
  }
  Calendar c = Calendar.getInstance(  );
  if (!yyok)
    yy = c.get(Calendar.YEAR);
 
  String mmString = request.getParameter("month");
  if (mmString == null) {
    mm = c.get(Calendar.MONTH);
  } else {
    for (int i=0; i<months.length; i++)
      if (months[i].equals(mmString)) {
        mm = i;
        break;
      }
  }
%>
 
<form method=post action="CalendarPage.jsp">
  Month: <select name=month>
  <% for (int i=0; i<months.length; i++) {
    if (i==mm)
      out.print("<option selected>");
    else
      out.print("<option>");
    out.print(months[i]);
    out.println("</option>");
  }
  %>
  </select>
  Year (4-digit):
    <input type="text" size="5" name="year"
      value="<%= yy %>"></input>
  <input type=submit value="Display">
</form>
<%!
  /** The names of the months */
  String[] months = {
    "January", "February", "March", "April",
    "May", "June", "July", "August",
    "September", "October", "November", "December"
  };
 
  /** The days in each month. */
  int dom[] = {
      31, 28, 31, 30,  /* jan feb mar apr */
      31, 30, 31, 31, /* may jun jul aug */
      30, 31, 30, 31  /* sep oct nov dec */
  };
%>
 
<%
  /** The number of days to leave blank at the start of this month */
  int leadGap = 0;
%>
<table border=1>
<tr><th colspan=7><%= months[mm] %>  <%= yy %></tr>
 
<%    GregorianCalendar calendar = new GregorianCalendar(yy, mm, 1); %>
 
<tr><td>Su<td>Mo<td>Tu<td>We<td>Th<td>Fr<td>Sa</tr>
 
<%
    // Compute how much to leave before the first.
    // getDay(  ) returns 0 for Sunday, which is just right.
    leadGap = calendar.get(Calendar.DAY_OF_WEEK)-1;
 
    int daysInMonth = dom[mm];
    if (calendar.isLeapYear(calendar.get(Calendar.YEAR)) && mm == 1)
      ++daysInMonth;
 
    out.print("<tr>");
 
    // Blank out the labels before 1st day of month
    for (int i = 0; i < leadGap; i++) {
      out.print("<td>&nbsp;");
    }
 
    // Fill in numbers for the day of month.
    for (int i = 1; i <= daysInMonth; i++) {
 
      out.print("<td>");
      out.print(i);
      out.print("</td>");
 
      if ((leadGap + i) % 7 == 0) {    // wrap if end of line.
        out.println("</tr>");
        out.print("<tr>");
      }
    }
%>
</tr>
</table>


For another example, Example 18-13 shows the list of terms and definitions from First Servlet: Generating an HTML Page done as a JSP.


Example 18-13: terms.jsp

<HTML>
<HEAD>
  <TITLE>Ian Darwin's Computer Terms and Acronyms</TITLE>
  <%@ page import="java.io.*" %>
</HEAD>
<BODY BGCOLOR=white>
<H1>Ian Darwin's Computer Terms and Acronyms</h2>
<TABLE BORDER=2>
<TR><TH>Term<TH>Meaning</TR>
  <%
  // This part of the Servlet generates a list of lines like
  //  <TR> <TD>JSP <TD>Java Server Pages, a neat tool for ...
 
  // Filenames like this must NOT be read as parameters, since that
  // would allow any script kiddie to read any file on your system!!
  // In production code they would be read from a Properties file.
  String TERMSFILE = "/var/www/htdocs/hs/terms.txt";
 
  TermsAccessor tax = new TermsAccessor(TERMSFILE);
  Iterator it = tax.iterator(  );
  while (it.hasNext(  )) {
    Term t = it.next(  );
    out.print("<TR><TD>");
    out.print(t.term);
    out.print("</TD><TD>");
    out.print(t.definition);
    out.println("</TD></TR>");
  }
  %>
</TABLE>
<HR></HR>
<A HREF="/servlet/TermsServletPDF">Printer-friendly (Acrobat PDF) version</A>
<HR></HR>
<A HREF="mailto:compquest@darwinsys.com?subject=Question">Ask about another term</A>
<HR></HR>
<A HREF="index.html">Back to HS</A> <A HREF="../">Back to DarwinSys</A>
<HR></HR>

Pages: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11

Next Pagearrow