Content
Chapter 2: Servlets
Whenever a simple idea is elegant and powerful enough that its applications open development paths that were previously closed, the architects of said idea might truly feel that their work has been a benefit to the development community. The concept of servlets falls into that category, vaguely bringing back memories of the old Othello game slogan: "a minute to learn, a lifetime to master."
Client/Server Defined
A server is an application that contains business logic components that can performs a particular task when requested by a client. The client and server can communicate in several ways - as an example, network communication is required if the client is located on a different computer than the server.
In some cases, the business logic of a server application is hard-coded into the server application making it difficult to modify if a different behavior is required. J2EE servlets represents another approach, where business logic can be added and controlled in a standard manner.
Servlet Advantage
Servlets are pieces of business logic that can be plugged into any server process that accepts a stream of text or binary data as its only argument and that produces a stream of text or binary data as a result. In a world of many binary, platform-specific servers, servlets are reusable platform- and server-independent building blocks of business logic.
The compelling idea behind servlets is their simplicity and the services provided in a similar way to all servlets by the runtime environment they execute within (known as a "container" in Java 2 Enterprise Edition [J2EE] lingo).
In Programmer's Terms...
There are two demands on a servlet
- It must implement the interface
javax.servlet.Servlet - As a result, it must provide a business logic implementation to the method
public void service(ServletRequest req, ServletResponse res)
When tailored for usage within a web server, one rarely uses the ServletRequest and ServletResponse interfaces directly, but instead their subclasses HttpServletRequest and HttpServletResponse respectively. One also frequently extends the abstract superclass HttpServlet instead of directly implementing the Servlet interface. Therefore, the proverbial "Hello World" servlet is a trivial thing indeed:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorldServlet extends HttpServlet
{
public void service(HttpServletRequest req,
HttpServletRequest res)
{
// Get a Write which will send output
// to the response stream.
PrintWriter out = res.getWriter();
// Print the important message.
out.println("Hello World");
}
}

