O'Reilly logo

JavaServer Pages, Second Edition by Hans Bergsten

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Why Use JSP?

In the early days of the Web, the Common Gateway Interface (CGI) was the only tool for developing dynamic web content. However, CGI is not an efficient solution. For every request that comes in, the web server has to create a new operating-system process, load an interpreter and a script, execute the script, and then tear it all down again. This is very taxing for the server and doesn’t scale well when the amount of traffic increases.

Numerous CGI alternatives and enhancements, such as FastCGI, mod_perl from Apache, NSAPI from Netscape, ISAPI from Microsoft, and Java servlets from Sun Microsystems, have been created over the years. While these solutions offer better performance and scalability, all these technologies suffer from a common problem: they generate web pages by embedding HTML directly in programming language code. This pushes the creation of dynamic web pages exclusively into the realm of programmers. JavaServer Pages, however, changes all that.

Embedding Dynamic Elements in HTML Pages

JSP tackles the problem from the other direction. Instead of embedding HTML in programming code, JSP lets you embed special active elements into HTML pages. These elements look similar to HTML elements, but behind the scenes they are actually componentized Java programs that the server executes when a user requests the page. Here’s a simple JSP page that illustrates this:

<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<html>
  <body bgcolor="white">
  
  <jsp:useBean id="clock" class="java.util.Date" />
                  <c:choose>
                  <c:when test="${clock.hours < 12}">
      <h1>Good morning!</h1>
    </c:when>
                  <c:when test="${clock.hours < 18}">
      <h1>Good day!</h1>
    </c:when>
                  <c:otherwise>
      <h1>Good evening!</h1>
    </c:otherwise>
                  </c:choose>
  Welcome to our site, open 24 hours a day.
  </body>
</html>

This page inserts a different message to the user based on the time of day: “Good morning!” if the local time is before 12 P.M., “Good day!” if between 12 P.M. and 6 P.M., and “Good evening!” otherwise. When a user asks for this page, the JSP-enabled web server executes the logic represented by the highlighted JSP elements and creates an HTML page that is sent back to the user’s browser. For example, if the current time is 8:53 P.M., the resulting page sent from the server to the browser looks like this:

<html>
  <body bgcolor="white">
  <h1>Good evening!</h1>
    Welcome to our site, open 24 hours a day.
  </body>
</html>

A screen shot of this result is shown in Figure 1-2.

The output of a simple JSP page

Figure 1-2. The output of a simple JSP page

In addition to the HTML-like JSP elements, a JSP page can also contain Java code embedded in so-called scripting elements . This feature has been part of the JSP specification from the very first version, and it used to be convenient for simple conditional logic. With the introduction of the new JSP Standard Tag Library (JSTL), however, Java code in a page is rarely needed. In addition, embedding too much code in a web page is no better than using HTML elements in a server-side program, and often leads to a web application that is hard to maintain and debug. The examples in this book rarely use scripting elements, but they are described in detail in Chapter 15.

Compilation

Another benefit that is important to mention is that a JSP page is always compiled before it’s processed by the server. Remember that older technologies such as CGI/Perl require the server to load an interpreter and the target script each time the page is requested. JSP gets around this problem by compiling each JSP page into executable code the first time it’s requested (or on demand), and invoking the resulting code directly on all subsequent requests. When coupled with a persistent Java virtual machine on a JSP-enabled web server, this allows the server to handle JSP pages much faster.

Using the Right Person for Each Task

As I alluded to earlier, JSP allows you to separate the markup language code, such as HTML, from the programming language code used to process user input, access a databases and perform other application tasks. One way this separation takes place is through the use of the JSP standard and custom elements; these elements are implemented with programming code and used the same way as page markup elements in regular web pages.

Another way to separate is to combine JSP with other J2EE technologies. For example, Java servlets can handle input processing, Enterprise JavaBeans (EJB) can take care of the application logic, and JSP pages can provide the user interface.

This separation means that with JSP, a typical business can divide its efforts among two groups that excel in their own areas of expertise: a Java web development team with programmers who implement the application logic as servlets, EJBs and custom JSP elements, and page authors who craft the specifics of the interface and use the powerful custom elements without having to do any programming. We’ll talk more about this benefit as we move through the book, although I should reiterate that the first half of the book is devoted more to those without programming experience, while the second half is for programmers who wish to combine JSP with other technologies and create their own JSP elements.

Integration with Enterprise Java APIs

Finally, because JavaServer Pages are built on top of the Java Servlets API, JSP has access to all the powerful Enterprise Java APIs, including:

  • JDBC

  • Remote Method Invocation (RMI) and OMG CORBA support

  • JNDI (Java Naming and Directory Interface)

  • Enterprise JavaBeans (EJB)

  • JMS (Java Message Service)

  • JTA (Java Transaction API)

  • JAXP (Java API for XML Processing)

  • JavaMail

This means that you can easily integrate JavaServer Pages with your existing Java Enterprise solutions.

Other Solutions

At this point, let’s digress and look at some other solutions for dynamic web content. Some of these solutions are similar to JSP, while others are descendants of older technologies. Many don’t have the unique combination of features and portability offered by JavaServer Pages.

Active Server Pages (ASP)

Microsoft’s Active Server Pages (ASP) is a popular technology for developing dynamic web sites. Just like JSP, ASP lets a page author include logic, such as VBScript and JScript code, in regular web pages to generate the dynamic parts. For complex code, COM (ActiveX) components written in a programming language such as C++ can be invoked by the scripting code. The standard distribution includes components for database access and more, and other components are available from third parties. When an ASP page is requested, the code in the page is executed by the server. The result is inserted into the page, and the combination of the static and dynamic content is sent to the browser.

ASP.NET, the latest version of ASP, adds a number of new features. As an alternative to scripting, dynamic content can be generated by HTML/XML-like elements similar to JSP action elements. For improved performance, ASP.NET pages are compiled as opposed to interpreted, and Common Language Runtime (CLR) languages, such as C#, JScript.NET, and Visual Basic.NET, are used instead of the scripting languages supported in previous ASP-versions.

The classic ASP version is bundled with Microsoft’s Internet Information Server (IIS). Due to its reliance on native COM code as its component model, it’s primarily a solution for the Windows platform. Limited support for other platforms, such as the Apache web server on Unix, is available through third-party products such as Sun Chili!Soft ASP (Sun Microsystems, Inc.) and InstantASP (Halcyon Software). ASP.NET is a part of the complete .NET platform, with the potential for better support on non-Windows platforms. You can read more about ASP and ASP.NET on Microsoft’s web site, http://www.microsoft.com.

PHP

PHP[1] is an open source web scripting language. Like JSP and ASP, PHP allows a page author to include scripting code in regular web pages to generate dynamic content. PHP has a C-like syntax with some features borrowed from Perl, C++, and Java. Complex code can be encapsulated in both functions and classes. A large number of predefined functions are available as part of PHP, such as accessing databases, LDAP directories, and mail servers, creating PDF documents and images, and encrypting and decrypting data. PHP 4, the current version, compiles a page when it’s requested, executes it and merges the result of executing the scripts with the static text in the page, before it’s returned to the browser.

PHP is supported on a wide range of platforms, including all major web servers, on operating systems like Windows, Mac, and most Unix flavors, and with interfaces to a large number of database engines. More information about PHP is available at http://www.php.net.

ColdFusion

Macromedia’s ColdFusion product is another popular alternative for generating dynamic web content. The dynamic parts of a page are generated by inserting HTML/XML-like elements, known as the ColdFusion Markup Language (CFML), into web pages. CFML includes a large set of elements for tasks such as accessing databases, files, mail servers, and other web servers, as well as conditional processing elements such as loops. The latest version of ColdFusion also includes elements for communication with Java servlets and Enterprise JavaBeans. Custom elements can be developed in C++ or Java to encapsulate application-specific functions, and CFML extensions are available from third parties. ColdFusion didn’t initially support scripting languages, but since ColdFusion 4.5, JavaScript-like code can be embedded in the web pages in addition to the CFML tags.

The ColdFusion 5, Enterprise Edition, is supported on Windows, Solaris, HP/UX and Linux, for all major web servers and databases. For more information, visit Macromedia’s web site at http://www.macromedia.com/.

Java servlet template engines

A Java servlet template engine is another technology for separating presentation from processing. When servlets became popular, it didn’t take long before developers realized how hard it was to maintain the presentation part when the HTML code was embedded directly in the servlet’s Java code. As a result, a number of so-called template engines have been developed as open source products to help get HTML out of the servlets.

Template engines are intended to be used with pure code components (servlets) and to use web pages with scripting code only for the presentation part. Requests are sent to a servlet that processes the request, creates objects that represent the result, and calls on a web page template to generate the HTML to be sent to the browser. The template contains scripting code similar to the alternatives described earlier. The scripting languages used by these engines are less powerful, however, since scripting is intended only for reading data objects and generating HTML code to display their values. All the other products and technologies support general-purpose languages, which can (for better or for worse) be used to include business logic in the pages.

Two popular template engines are Velocity (http://jakarta.apache.org/velocity/) and FreeMarker (http://freemarker.sourceforge.net/).

The JSP Advantage

JSP 1.2 combines the most important features found in the alternatives:

  • JSP supports both scripting- and element-based dynamic content and allows programmers to develop custom tag libraries to satisfy application-specific needs.

  • JSP pages are compiled for efficient server processing.

  • JSP pages can be used in combination with servlets that handle the business logic, the model supported by Java servlet template engines.

In addition, JSP has a couple of unique advantages that make it stand out from the crowd:

  • JSP is a specification, not a product. This means vendors can compete with different implementations, leading to better performance and quality. It also leads to a less obvious advantage, namely that when so many companies have invested time and money in the technology, chances are it will be around for a long time, with reasonable assurances that new versions will be backward-compatible; with a proprietary technology, this is not always a given.

  • JSP is an integral part of J2EE, a complete platform for enterprise class applications. This means that JSP can play a part in the simplest applications to the most complex and demanding.



[1] The precursor to PHP was a tool called Personal Home Page. Today PHP is not an acronym for anything; it’s simply the name for this product.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required