Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 38 ยท Applications

Web Servers and Servlets

Build web apps with Racket's web-server: request and response structs, dispatch-rules routing, X-expressions for HTML, forms, and a JavaScript routing and templating stand-in.

Racket comes with a web server library written in Racket. A web application there is, at its core, a function from a request to a response, and HTML is written as plain data (nested lists called X-expressions), not as templates in another language. That makes small web apps pleasantly short, and it connects with what you learned about code as data.

This lesson covers serve/servlet, building HTML with X-expressions, routing with dispatch-rules, reading forms, and the idea behind Racket's unusual continuation-based servlets. Our site cannot run a Racket server, so the code is read-only, and the runnable blocks are JavaScript stand-ins for the routing and HTML parts.

A first servlet

RACKET
#lang racket
(require web-server/servlet
         web-server/servlet-env)

(define (start request)
  (response/xexpr
   `(html
     (head (title "Hello"))
     (body (h1 "Hello from Racket")
           (p "You asked for: "
              ,(url->string (request-uri request)))))))

(serve/servlet start
               #:port 8000
               #:servlet-regexp #rx"")

start receives a request struct and returns a response. response/xexpr converts an X-expression to an HTML response with the right headers. The quasiquote ` and unquote , from the earlier lesson are how data is mixed into the page. An X-expression is a list: tag symbol, optional attribute list ([class "big"]), then children.

RACKET
`(a ([href "/about"] [class "link"]) "About us")

Because the output is data, special characters in strings are escaped when the HTML is generated, which protects you from many injection bugs that string-concatenated HTML invites.

Routing with dispatch-rules

Real apps need several URLs. web-server/dispatch provides dispatch-rules, which maps URL patterns and methods to handler functions:

RACKET
(require web-server/dispatch)

(define-values (app-dispatch app-url)
  (dispatch-rules
   [("") home]
   [("hello" (string-arg)) hello]
   [("items" (integer-arg)) show-item]
   [("items" "new") #:method "post" create-item]))

(define (home req) (response/xexpr '(html (body (h1 "Home")))))
(define (hello req name)
  (response/xexpr `(html (body (h1 ,(string-append "Hello, " name))))))
(define (show-item req id)
  (response/xexpr `(html (body (p ,(format "Item #~a" id))))))

(integer-arg) converts the path segment to an integer and rejects non-numbers. app-url is the reverse: (app-url show-item 7) generates "/items/7", so you never hard-code links. This pairing of routing and link generation prevents broken links when you rename a route.

Forms and request data

Form data arrives in the request bindings:

RACKET
(define (greet req)
  (define bindings (request-bindings req))
  (define name (or (extract-binding/single 'name bindings) "stranger"))
  (response/xexpr `(html (body (p ,(string-append "Hi " name))))))

Treat all form input as untrusted: validate numbers with string->number (it returns #f on failure), limit lengths, and use contracts on your internal functions.

Stand-in: routing and templating in JavaScript

The block below builds a mini version of the same architecture in JavaScript: an xexpr renderer that escapes text, and a router that matches patterns like /items/:id. It handles fake requests so you can run it in the console.

JS Stand-in: X-expressions and dispatch rules

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The <script> in the third request is turned into &lt;script&gt; by the renderer, the same protection response/xexpr offers.

Continuations in servlets

The Racket server has a distinctive feature: a servlet can pause in the middle of a handler, send a form to the browser, and continue when the user submits it, with all local variables intact.

RACKET
(define (start request)
  (define a (string->number (get-field "first number" request)))
  (define b (string->number (get-field "second number" request)))
  (response/xexpr `(html (body (p ,(format "Sum: ~a" (+ a b)))))))

Here get-field stands for a helper you would write yourself (it is not a library function). It would call send/suspend, which captures the continuation, embeds a URL for it in the form, and later resumes with the browser's answer. The code reads like a console program: "ask for a, ask for b, compute". This is the continuation material from call/cc applied to the web. It is powerful for multi-step flows, but it stores continuations on the server, so production apps often prefer stateless routing (dispatch-rules) and keep state in a database or in stateless servlets.

sequenceDiagram
  participant B as Browser
  participant S as Servlet
  B->>S: GET /
  S-->>B: form 1 (continuation saved, URL k1)
  B->>S: POST /k1 (first number)
  S-->>B: form 2 (continuation saved, URL k2)
  B->>S: POST /k2 (second number)
  S-->>B: result page

Each form submission resumes the handler where it paused.

Deployment notes

For production, run the server behind a reverse proxy, serve static files separately (serve/servlet has #:extra-files-paths), set timeouts, and avoid serve/servlet's development conveniences (auto-launching a browser). Use raco exe or raco distribute to package a standalone executable.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is an X-expression?

    X-expressions are nested lists that response/xexpr converts to HTML, escaping text automatically.
  2. 2. What does (integer-arg) do in dispatch-rules?

    It parses that segment and passes the integer to the handler; a non-number does not match the rule.
  3. 3. Why is generating HTML from data safer than concatenating strings?

    The renderer escapes <, & and quotes in text, so user input cannot become markup.
  4. 4. What does send/suspend make possible?

    It captures the handler's continuation behind a URL, so the code can continue after the next request.

Summary

  • A servlet is a function from a request to a response; serve/servlet runs it.
  • HTML is built from X-expressions and quasiquote, and text is escaped automatically.
  • dispatch-rules handles routing and app-url generates matching links.
  • Validate all form input; string->number returns #f on bad data.
  • Continuation-based servlets write multi-step flows like console programs, at the cost of server-side state.

Next: Concurrency and Places