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
- Your
handle(connection, request)is asked first, if you gave the block ahandlerclass. Return a response, or null to pass. - A WebSocket handshake for a path named in an
upgradeline is handed to that WebSocket server. - Paths under
/api/go to the built-in endpoints. - A
routemaps the URL to a file. - Otherwise the path is looked up under the
homedirectory, or under amount. - Nothing found: a 404 page.
Static files
- A directory serves its
index.html. - The content type comes from the file extension (HTML, CSS, JS, JSON, images, fonts, audio, video, PDF, WebAssembly and more; anything unknown is
application/octet-stream). - A request can never leave the home or mounted directories:
../is resolved and refused, however it is encoded. - Files and directories whose names start with a dot (
.git,.env) are never served. - Files up to 64 MB are served. Large files do not block other clients.
- To replace the built-in error pages, put
pages/status/404.html(or500.html) in the home directory.
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
| Member | Is |
|---|---|
method, is("POST") | The HTTP method. |
path | The 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
| Factory | Makes |
|---|---|
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
| Endpoint | Does |
|---|---|
GET /api/status | JSON: 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/register | Create an account. Only with a login block. |
POST /api/login | Log in; sets the session cookie. |
POST /api/logout | End 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
- Request headers up to 16 KB; bodies up to
max-body(1 MB by default). Larger requests get 431 or 413. - Chunked request bodies are not supported; send a
Content-Length. - Connections are kept alive between requests and closed after 30 seconds idle.
- Every response carries
Content-Length,X-Content-Type-Options: nosniffandServer: JBend/2.0.0. - HTTPS is not built in. Put JBend behind a reverse proxy that terminates TLS; see Deployment.
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.