Home
What's New
Dev Tools
Services
Feedback
Site Map

Overview of Java Servlets

Common Gateway Interface (CGI) was one of the first tools for creating webpages with dynamic content.  In fact, from reading many early Internet books or articles, one would have the impression that CGI was the only way to create dynamic content.  Over time, vendors introduced alternative methods for creating dynamic content.   Netscape introduced server-side JavaScript while Microsoft introducted Active Server Pages (ASP).

In 1997, Sun introduced Servlets to create webpages with dynamic content.   Servlets are used within a web server (in place of CGI scripts) and run inside the Java Virtual Machine (JVM) on the server.  Unlike applets, they do not require support for Java in the web browser.  Servlets can be run on all major web servers (either directly or via widely available third-party plug-ins).

In creating webpages with dynamic content, Servlets also provide an infrastructure to parse/decode the user-submitted HTML form, handle cookies, etc.  As such, the Servlet can manage all the presentation aspects of the web application.

Servlets can access database directly (as might be appropriate for a simple web application) or Servlets can derive their dynamic content via a sepearate business layer running on an application server (as would be appropriate for larger web applications).

Since Servlets follow the standard Sun-defined API, Servlet application code is portable across web servers.

Servlet Code Sample

The following Servlet code sample generates a webpage which generates a webpage that says "Welcome back, username" (where username is the current user).

import java.io.*;
import javax.sertlet.*;
import javax.servlet.*;
public class WelcomeUser extends HttpServlet {
  public void doGet(HttpServletRequest req,
    HttpServletResponse res) throws ServletException, IOException {
    res.setContentType(“text/html”);
    PrintWriter out = res.getWriter();
    out.println(“<html>”);
    out.println(“<body>”);
    out.println(“<H1> Welcome back,”);
    out.print(“String user = ”);
    out.println(“(String) session.getAttribute(‘user’)”);
    out.println(user);
    out.println(“</H1>”);
    out.println(“</body>”);
    out.println(“</html>”);
  }
}

Current Usage

Today, Servlets are mainly used as controllers in Model-View-Controller application implementations.

... back to  Java Topics 


Copyright 1997-2017, Woodger Computing Inc.