Writing Servlets

When a request URL matches the servlet filter, the Web server generates its response dynamically, (see the section titled ``Directories'' for more explanation, and the section titled ``Directory Structure'' and the section titled ``Paths'' for administrative details). Instead of serving the files in this directory verbatim, the server evaluates the file as a scheme program to produce output. Servlets are (by default) loaded in a case-sensitive manner. (Search in help-desk for read-case-sensitive.)

The path part of the URL supplies the file path to the servlet relative to the servlets directory. However, paths may also contain extra path components that servlets may use as additional input. For example all of the following URLs refer to the same servlet:

The server supports two forms of servlets. For useful procedures to handle Web data, see the section titled ``Servlet Library''.

9.1  Module-Based Servlets

A module-based servlet is a module that provides three values: an interface-version, a timeout, and a start procedure.

(module a-module-servlet mzscheme
  (provide interface-version timeout start)
  
  (define interface-version 'v1)
  
  (define timeout +inf.0)
  
  ; start : request -> response
  (define (start initial-request)
    `(html (head (title "A Test Page"))
           (body ([bgcolor "white"])
                 (p "This is a simple module servlet.")))))

interface-version : symbol

The interface-version is a symbol indicating how the server should interact with the servlet. The only supported value is 'v1 at this time.

timeout : number

The timeout is the number of seconds the server will allow the servlet to run before shutting it down. Large values consume more memory, while smaller values annoy users by forcing them to restart their session. The value can be adjusted dynamically by calling the adjust-timeout! procedure. For more information, see the section titled ``Timeouts'' and section IGNORE.

start

   request -> response
   (define (start request) ···)

The start function consumes a request and produces a response. Each time a client visits the URL associated with the beginning of the servlet, the server calls the start function with the request sent from the browser. The server then sends the response produced by the start function back to the browser.

9.2  Unit-Based Servlets

A unit-based servlet is a unit/sig that imports the servlet^ signature and exports nothing. (See the manual for unit/sig and signatures.) To construct a signed unit with the appropriate imports, the servlet must require the two modules providing unit/sigs and the servlet signature:

(require (lib "unitsig.ss")
         (lib "servlet-sig.ss" "web-server"))
(unit/sig ()
  (import servlet^)
   ;;; ...insert servlet code here...
)

Evaluating

(require (lib "servlet-sig.ss" "web-server"))

loads the servlet^ signature which contains the import initial-request of type request.