Most programmers will be familiar with the concept of server-side programming. Content can be created at the client end, through JavaScript, Dynamic HTML, or applets – but it can also be created at the server end through CGI scripts, server side applications, and now servlets!

Servlets are pieces of Java code that work at the server end. Servlets have all the access to resources on the server that a CGI script do, and aren't normally limited by the restrictions on file and network access that Java applets have traditionally been held back by. Servlets also offer substantial performance advantages for developers and webmasters, because unlike CGI scripts, do not fork off additional processes each time a request is made from a browser.

Servlets may take a little while to approach the same amount of usage as CGI scripts, but they are growing in popularity. Aside from the obvious advantage of portability, the performance advantages are significant, and its likely that in the future the use of Java servlets will become widespread. Developers keen to adopt skills should certainly focus on this new trend in server side programming, as the number of developers with servlet experience is (currently), small.

Here is a sample servlet, to illustrate just how easy it is to write server-side code in Java. For this example, I've written a servlet that outputs the obligatory 'Hello World!' message.


// Import servlet packages (requires JDK1.2 or servlet toolkit)
import javax.servlet.*;
import javax.servlet.http.*;

public class MyFirstServlet extends HttpServlet 
    // We override the doGet method, from HttpServlet, to
    // provide a custom GET method handler
    public void doGet (HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException
            ServletOutputStream out = res.getOutputStream();

            out.println ("Hello World!");

    public String getServletInfo() {
        return "MyFirstServlet";

Can you guess what this servlet would do, when invoked? The response sent back by the servlet will have a MIME type of text/plain, and will consist of a single line of text. All that you need to do is to then install the servlet into a servlet compatible web-server, and then it runs just like a CGI script would. Support for servlets is increasing, and there are currently many web servers that support servlets (including O'Reilly's WebSite, and Sun's JavaWebServer).

Posted in: Java

Related FAQ's

Marius Ion ANGEL HOT SOFT LLC (800) 316-7677