Web server (HTTP)

com.server.protocol.HTTP, com.server.web.Request, com.server.web.Response

The webserver block starts an HTTP/1.1 server implemented in com.server.protocol.HTTP: request parsing, keep-alive, static files, routes, cookies, sessions and a small JSON API. It answers GET, HEAD and POST.

What happens to a request

  1. Your handle(connection, request) is asked first, if you gave the block a handler class. Return a response, or null to pass.
  2. A WebSocket handshake for a path named in an upgrade line is handed to that WebSocket server.
  3. Paths under /api/ go to the built-in endpoints.
  4. A route maps the URL to a file.
  5. Otherwise the path is looked up under the home directory, or under a mount.
  6. Nothing found: a 404 page.

Static files

Page variables

A set line in the block defines a variable, and {{jbend:name}} in any served HTML, JS or CSS file is replaced with its value. It is meant for the few things a page cannot work out by itself:

webserver:
listen 8080
set ws-address wss://example.com/ws
<script>var ws = new WebSocket("{{jbend:ws-address}}");</script>

Handlers

Extend HTTP, override handle, and name the class with handler:

public class Shop extends HTTP {

    public Shop(String home, int port) { super(home, port); }

    @Override
    public Response handle(ServerConnection c, Request req) {
        if (req.path.equals("/api/time"))
            return Response.json("{\"now\":" + System.currentTimeMillis() + "}");

        if (req.path.equals("/account")) {
            if (req.user() == null)
                return Response.redirect("/login.html");
            return Response.html("<h1>Hello " + Response.htmlEscape(req.user()) + "</h1>");
        }

        if (req.path.equals("/contact") && req.is("POST")) {
            String message = req.param("message", "");
            // ... store it ...
            return Response.text("Thanks.");
        }
        return null;
    }
}

Request

MemberIs
method, is("POST")The HTTP method.
pathThe URL path, decoded, without the query string.
param(name), param(name, fallback)A field from the query string or a URL-encoded form body.
header(name)A request header, case-insensitive.
cookie(name)A cookie's value.
body, bodyText()The raw body, for JSON or anything else.
user()The logged-in account name, or null.

Response

FactoryMakes
Response.html(text), .text(text), .json(text)A 200 with that content type.
Response.bytes(contentType, data)A 200 with any content.
Response.redirect(location)A 302.
Response.status(code, text)Any status with a plain-text body.
.header(name, value), .cookie(cookie), .withStatus(code)Chained onto any of the above.
Response.htmlEscape(s), Response.jsonEscape(s)Escaping for text you put into HTML or a JSON string. Use them for anything a user typed.

Cookies

return Response.html(page).cookie(new Cookie("theme", "dark").setAge(30 * 86400));

setHttpOnly(true) hides a cookie from scripts and setSecure(true) restricts it to HTTPS. Cookies default to Path=/ and SameSite=Lax.

Answering after a database query

A handler must return quickly, and a query's result arrives later on another thread. Return Response.DEFERRED and call respond from the query's callback:

@Override
public Response handle(final ServerConnection c, Request req) {
    if (!req.path.equals("/api/products"))
        return null;
    new ServerQuery(c, "SELECT name, price FROM products WHERE category = ?", req.param("category", "all")) {
        public void done() {
            if (failed()) { respond(c, Response.status(500, "Database error")); return; }
            StringBuilder json = new StringBuilder("[");
            for (int i = 0; i < responseSize(); i++)
                json.append(i > 0 ? "," : "").append("{\"name\":\"").append(Response.jsonEscape(value(i, "name")))
                    .append("\",\"price\":").append(value(i, "price")).append("}");
            respond(c, Response.json(json.append("]").toString()));
        }
    };
    return Response.DEFERRED;
}

A deferred request that is never answered is closed after 60 seconds.

Built-in endpoints

EndpointDoes
GET /api/statusJSON: application name and version, uptime, each server's port and connection counts, database state, session count, and anything added with putStatus. Turn it off with status off.
POST /api/registerCreate an account. Only with a login block.
POST /api/loginLog in; sets the session cookie.
POST /api/logoutEnd the session.
GET /api/me{"user":"name"} or {"user":null}.

The account endpoints are described in Accounts and sessions. Your handle runs first, so you can replace any of these by answering the same path yourself.

WebSockets on the same port

Browsers, firewalls and reverse proxies are simplest with one port. upgrade /ws 8081 makes the web server pass WebSocket handshakes for /ws to the WebSocket server on local port 8081 and relay the connection, so the WebSocket server can stay bound to 127.0.0.1. The visitor's address is passed along in X-Forwarded-For.

Limits and details

Code written for JBend 1.x

The 1.x hooks still work: processGET(c, uri, resource, fields, values) may return the bytes of a complete hand-built response, and processPOST(c, uri, packetID, fields, values) is called for form posts carrying a numeric packet field. The constants HTTP.HTTP_OK and friends, fileHTML and multiHTMLResponse are still there. New code should use handle.