Chapter 18. Web Server Java: Servlets and JSP

Introduction

This chapter covers Web Server Java, but you won’t find anything about writing CGI programs in Java here. Although it would be entirely possible to do so, it would not be efficient. The whole notion of CGI programs is pretty much passe. Every time a CGI program is invoked, the web server has to create a new heavyweight process in which to run it; this is inefficient. If it’s interpreted in Java, the program has to be translated into machine code each time; this is even more inefficient.

Today’s trend is toward building functionality into the web server: Microsoft ASP, PHP3, Java servlets, and JavaServer Pages™ (JSP[40]) are examples of this. None of these normally requires a separate process to be created for each request; the Java-based solutions run in a thread (see Chapter 24) inside the web server, and the Java bytecode need only be translated into machine code once in a long while, assuming a just-in-time (JIT) runtime system. Naturally, this book concentrates on the Java solutions.

We’ll use two examples in this chapter. Consider the task of displaying a web page with five randomly chosen integer numbers (lottery players love this sort of thing). The Java code you need is simple:

// Part of file netweb/servlets_jsp/FiveInts.java 
Random r = new Random(  ); 
for (int i=0; i<5; i++) 
    System.out.println(r.nextInt(  ));

But of course you can’t just run that and save its output into an HTML file because you want each person seeing ...

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.