# Add e-signatures and clickwrap with Java

> Build a signup clickwrap in plain Java with the JDK's HttpClient and HttpServer, a signed cookie and Gson, calling the Esign Comply REST API. No framework.

Source: https://esigncomply.com/docs/quickstart/java

Last updated November 26, 2026

To add e-signatures and clickwrap with Java, call the REST API with the JDK's `HttpClient` and the secret key: there is no package. One class with no framework creates the session, keeps the pinned versions in a signed cookie, and confirms the record. The browser SDK attaches to your checkbox. Esign Comply seals each acceptance as an independent record.

Follow the steps and each signature your app records is a valid electronic signature under the ESIGN Act, state UETA laws and New York's ESRA, and your clickwrap is built the way courts require: clear notice of the terms, an unmistakable act of assent, and a sealed record of both.

This page is plain Java with no framework. For Spring Boot, use the [Spring Boot quickstart](https://esigncomply.com/docs/quickstart/spring-boot.md).

Paste this prompt into Cursor, Claude Code or another AI coding tool to have it build the same integration:

```text copy="Copy prompt" open="cursor"
Add Esign Comply clickwrap to my Java app: a signup form where the user accepts the Terms of Service and the Privacy Notice with a checkbox and a button.

Read these first and follow them exactly. If something conflicts with existing code, or you are unsure how to implement a step, stop and ask. Do not invent API methods, packages or legal wording.
- https://esigncomply.com/docs/quickstart/java.md (the steps and the tested code for Java)
- https://esigncomply.com/setup.md (the order of API calls)
- https://esigncomply.com/auth.md (how to handle the keys)

Java facts
- There is no Esign Comply package for Java. Do not install or invent one. The server calls the REST API at https://esigncomply.com/v1 with java.net.http.HttpClient, Authorization: Bearer and the secret key.
- The browser SDK is a script tag: https://esigncomply.com/sdk/v1/esigncomply.js. It defines the global EsignComply.
- The secret key is in the environment variable ESIGNCOMPLY_API_KEY. Java does not read .env files. System.getenv returns null for a missing variable: stop at start with a message. Never print the key.
- HttpClient: set timeout() on every request (without it a request waits forever) and connectTimeout() on the client. It does not throw on 4xx and 5xx: read statusCode() and the error envelope. Pin HttpClient.Version.HTTP_1_1 unless the project already relies on HTTP/2: by default the client asks a plain-http server to upgrade to HTTP/2.
- The JDK has no JSON parser. Use the JSON library the project already has, or Gson. Never parse JSON with string functions. Read the API's snake_case fields into records, and declare livemode as Boolean, not boolean: a missing boolean is read as false.
- With com.sun.net.httpserver.HttpServer, call setExecutor: the default handles every request on one thread. Catch exceptions in the handler and answer 500: an exception that leaves the handler closes the connection with no answer.
- There is no session. Keep the signer ID and the pinned version IDs in a cookie signed with javax.crypto.Mac (HmacSHA256) and compare the signature with MessageDigest.isEqual. The visitor can read a signed cookie: put nothing secret in it.
- The JDK has no function that escapes HTML. Print the document HTML as it is, and check everything else you print.
- The page is on screen before the script has a session: render the checkbox disabled and enable it when observeAssent has resolved.

Build
1. Verify the key: GET /v1/usage with ESIGNCOMPLY_API_KEY. Stop if it fails.
2. Register the Terms of Service and the Privacy Notice as documents and publish one version of each from the documents in this project. If the project has none, register short sample documents and say so in your report. Never write or change the wording of the real documents. Create a profile: jurisdictions ["US-FED"], method "checkbox", assurance_level "L1".
3. Server: POST /api/ceremony calls POST /v1/sessions with an Idempotency-Key, saves the signer ID and the pinned version IDs in the signed cookie, and returns only clientToken, apiUrl and documents.
4. Server: GET /legal/terms and /legal/privacy render the html from GET /v1/documents/{id}/versions/{version_id}/content inside <article data-esc-document>, unmodified.
5. Browser: EsignComply.attach({ clientToken, apiUrl }), presentDocument for each link, observeAssent({ region, checkbox, submit }), then complete() from the user's real click.
6. Server: POST /api/signup/confirm calls GET /v1/records/{id} and requires: status is "recorded", "timestamped" or "anchored"; livemode is as expected; the signer ID and version IDs equal the ones in the signed cookie. Only then create the account.

Never
- Never pre-check the box, auto-submit, or call .click() on the user's behalf.
- Never use "By continuing" or "By clicking below" wording. The notice names the button by its label and each document by its registered name.
- Never put the secret key, or any call that uses it, in code that reaches the browser.
- Never show "signed" or "accepted" before the server has confirmed the record.
- Never fall back to an acceptance with no record when a session is refused.

Check before you report success
- Run: npx esigncomply check --url http://localhost:8000/signup --callback http://localhost:8000/api/signup/confirm
  Fix every finding marked "block". List every finding marked "warn".
- Report the files you created or changed, anything you did not implement and why, and the conformance summary.

Then add the rules block to this project's instruction file: https://esigncomply.com/rules.md
```

The rest of this page is the same integration by hand, in eight steps.

## Before you start

- A test API key. [Create an account](https://esigncomply.com/signup) with your email, no card, then choose **Create test key** in the dashboard. The key is shown once and starts with `esc_test_`. An AI agent with an agent token creates it with `POST /v1/agent/api-keys`: see the [agent account API](https://esigncomply.com/docs/api/agent.md).
- Nothing else from Esign Comply. Test mode works on `localhost` with no card and no domain, and the Free plan includes it in full.
- A JDK, version 21 or later. This page was run on Java 25, the current long-term support release, with no build tool.
- `curl` and `jq` for steps 2 and 3, and Node.js 20.19 or later for the conformance check in step 7.

## Step 1. Install

There is no artifact for the API. The server SDK exists for Node.js only, so a Java server calls the REST API directly. The JDK brings the HTTP client, the HTTP server and the HMAC. It has no JSON parser, so the project takes one library: Gson, as a single jar.

```bash
mkdir esigncomply-quickstart && cd esigncomply-quickstart
mkdir public lib
curl -sSLo lib/gson-2.15.0.jar \
  https://repo1.maven.org/maven2/com/google/code/gson/gson/2.15.0/gson-2.15.0.jar
sha256sum lib/gson-2.15.0.jar
```

```text
96d3dd843dc2911de01cdabcd50064cb9e860353102a0a78c96fd833d396fc7d  lib/gson-2.15.0.jar
```

That is the value Maven Central publishes beside the jar. In a project with Maven or Gradle, add `com.google.code.gson:gson:2.15.0` to the build you have and skip the download.

Why Gson. It is one jar of 316 KB, and nothing else was on the classpath in the test. It reads JSON into Java records, turns `version_id` into `versionId` with one setting, and skips fields the record does not name. Its README says it is in maintenance mode: bugs are fixed and large features are not added. For reading five fields that is enough. Jackson does the same job, and the Spring Boot quickstart reads the same JSON with it.

## Step 2. Set the key

Put the key in `.env` in the project folder. Java does not read this file: you load it into the shell that starts the app, and `App.java` reads the variables with `System.getenv`.

```bash
# .env (never commit this file)
ESIGNCOMPLY_API_KEY=esc_test_us_...
```

Step 4 keeps the pinned versions in a cookie that the app signs. Add the secret it signs with to the same file:

```bash
printf 'COOKIE_SECRET=%s\n' "$(head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n')" >> .env
```

Load the file into your shell for the commands in steps 2, 3 and 7, then check that the key works:

```bash
set -a; . ./.env; set +a
curl -s ${ESIGNCOMPLY_API_URL:-https://esigncomply.com/v1}/usage \
  -H "Authorization: Bearer $ESIGNCOMPLY_API_KEY" | jq '{plan_name, test_events}'
```

```json
{
  "plan_name": "Free",
  "test_events": {
    "used_this_month": 0,
    "quota_per_month": 500
  }
}
```

A `401` means the key is wrong or revoked: see [`invalid_api_key`](https://esigncomply.com/docs/api/errors.md#invalid_api_key). The rules for handling keys are in [/auth.md](https://esigncomply.com/auth.md).

## Step 3. Register a document version

Every record pins the exact version of each document by hash, so the documents are registered first. This block registers a Terms of Service and a Privacy Notice with one version each, and creates a profile: the Federal pack, a checkbox with a button, level L1. It is the same for every stack and needs `curl` and `jq`.

```bash
ESC=${ESIGNCOMPLY_API_URL:-https://esigncomply.com/v1}
KEY="Authorization: Bearer $ESIGNCOMPLY_API_KEY"
JSON="Content-Type: application/json"

# Two sample documents, one version each.
TERMS=$(curl -s $ESC/documents -H "$KEY" -H "$JSON" \
  -d '{"name":"Terms of Service","type":"terms"}' | jq -r .id); sleep 1
curl -s $ESC/documents/$TERMS/versions -H "$KEY" -H "$JSON" \
  -d '{"version_label":"1","language":"en","content":{"format":"markdown","text":"# Terms of Service\n\nThese are sample terms for a test."},"material_change":true}' \
  | jq -r .id; sleep 1
PRIVACY=$(curl -s $ESC/documents -H "$KEY" -H "$JSON" \
  -d '{"name":"Privacy Notice","type":"privacy_notice"}' | jq -r .id); sleep 1
curl -s $ESC/documents/$PRIVACY/versions -H "$KEY" -H "$JSON" \
  -d '{"version_label":"1","language":"en","content":{"format":"markdown","text":"# Privacy Notice\n\nThis is a sample privacy notice for a test."}}' \
  | jq -r .id; sleep 1

# A profile: Federal pack, checkbox plus button, L1.
PROFILE=$(curl -s $ESC/profiles -H "$KEY" -H "$JSON" \
  -d '{"name":"Signup","jurisdictions":["US-FED"],"method":"checkbox","assurance_level":"L1"}' | jq -r .id)

printf 'ESIGNCOMPLY_PROFILE_ID=%s\nESIGNCOMPLY_TERMS_ID=%s\nESIGNCOMPLY_PRIVACY_ID=%s\n' "$PROFILE" "$TERMS" "$PRIVACY"
```

It prints the two version IDs, then three lines with your own IDs:

```text
dv_YiWs9cmWoVSGp7ALPeZS
dv_bAYeA7QigKUH0iLhPpV7
ESIGNCOMPLY_PROFILE_ID=prof_SPVEgBT8a8Ror3mJ8M99
ESIGNCOMPLY_TERMS_ID=doc_bDgYFndAoC8tkeYibAVy
ESIGNCOMPLY_PRIVACY_ID=doc_mb2hnWKS0Qa7SKtucDW9
```

Add the three lines to `.env`, then load the file into your shell again. The pauses keep the script under the Free plan's 2 requests per second. Keep the names `Terms of Service` and `Privacy Notice`: the notice on your page names each document by its registered name, and rule [CR-02](https://esigncomply.com/docs/conformance.md#cr-02) checks that it does. With your own documents, publish the text you already have and change the notice to match. See [Documents](https://esigncomply.com/docs/api/documents.md) and [Profiles](https://esigncomply.com/docs/api/profiles.md).

## Step 4. Create a session on the server

`App.java` is the whole server: the signup page, the two document pages, the route that creates the session, and the route that confirms the record. The `esc` method is the entire client: one HTTPS call with the secret key that returns the status and the JSON read into a record, sent again only when the API answers `429`.

```java file="App.java"
// App.java
import static java.nio.charset.StandardCharsets.UTF_8;

import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.time.Duration;
import java.util.Base64;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class App {
    // There is no Java package for the API: these are plain HTTPS calls with the secret key, made with the JDK's HttpClient.
    static final String API = env("ESIGNCOMPLY_API_URL", "https://esigncomply.com/v1");
    static final String API_KEY = env("ESIGNCOMPLY_API_KEY", null);
    static final String PROFILE = env("ESIGNCOMPLY_PROFILE_ID", null);
    static final Map<String, String> DOCUMENTS = Map.of("terms", env("ESIGNCOMPLY_TERMS_ID", null), "privacy", env("ESIGNCOMPLY_PRIVACY_ID", null));
    static final byte[] COOKIE_SECRET = env("COOKIE_SECRET", null).getBytes(UTF_8);
    static final boolean LIVE = "true".equals(System.getenv("ESIGNCOMPLY_LIVE")); // set it in production only
    static final Set<String> SEALED = Set.of("recorded", "timestamped", "anchored");

    // The signer. In your app this is the signed-in user, or the account you are about to create.
    static final Map<String, String> SIGNER = Map.of(
        "external_id", "user_7c1d",
        "email", "dana@example.org",
        "name", "Dana Whitfield",
        "class", "consumer",
        "country", "US",
        "region", "US-CA");

    // The API's JSON is snake_case and the records below are camelCase: version_id becomes versionId. Unknown fields are skipped.
    static final Gson JSON = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();

    // HTTP/1.1 is pinned. By default the client asks a plain-http server to upgrade to HTTP/2 with every request.
    static final HttpClient HTTP = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).connectTimeout(Duration.ofSeconds(5)).build();

    // What this app reads from the API. Every field is an object, so one the API did not send is null, never false.
    record Doc(String versionId) {}
    record ApiError(String code) {}
    record Session(String clientToken, String apiUrl, List<Doc> documents, ApiError error) {}
    record Content(String versionId, String html) {}
    record Signer(String externalId) {}
    record Signed(String id, String status, Boolean livemode, Signer signer, List<Doc> documents) {}
    record Pinned(String signerId, List<String> versionIds) {}
    record Answer<T>(int status, T body) {}

    static String env(String name, String fallback) {
        String value = System.getenv(name);
        if (value != null && !value.isBlank()) return value;
        if (fallback == null) throw new IllegalStateException("Set the environment variable " + name);
        return fallback;
    }

    /** One call to the Esign Comply API. Returns the status and the JSON, read into the record you name. */
    static <T> Answer<T> esc(String method, String path, Object body, String idempotencyKey, Class<T> type) throws IOException, InterruptedException {
        // Without timeout() a request waits for its answer forever.
        HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(API + path))
            .timeout(Duration.ofSeconds(10))
            .header("Authorization", "Bearer " + API_KEY)
            .method(method, body == null ? HttpRequest.BodyPublishers.noBody() : HttpRequest.BodyPublishers.ofString(JSON.toJson(body)));
        if (body != null) request.header("Content-Type", "application/json");
        if (idempotencyKey != null) request.header("Idempotency-Key", idempotencyKey);
        for (int attempt = 1; ; attempt++) {
            // The client does not throw on 4xx and 5xx: the status is here, and the error envelope is the body.
            HttpResponse<String> response = HTTP.send(request.build(), HttpResponse.BodyHandlers.ofString());
            if (response.statusCode() != 429 || attempt == 3) {
                return new Answer<>(response.statusCode(), JSON.fromJson(response.body(), type));
            }
            // Over the rate limit: wait for Retry-After (1 to 5 seconds) and try again, twice at most. Nothing else is retried.
            long seconds = response.headers().firstValue("Retry-After").filter(value -> value.matches("\\d{1,4}")).map(Long::parseLong).orElse(1L);
            Thread.sleep(Duration.ofSeconds(Math.clamp(seconds, 1, 5)));
        }
    }

    // Server-owned state: there is no session, so it is a cookie this class signs with HMAC-SHA256.
    // The visitor can read it and cannot change it.
    static String sign(String payload) throws GeneralSecurityException {
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(COOKIE_SECRET, "HmacSHA256"));
        return HexFormat.of().formatHex(mac.doFinal(payload.getBytes(UTF_8)));
    }

    static String pinnedCookie(Pinned pinned) throws GeneralSecurityException {
        String payload = Base64.getUrlEncoder().withoutPadding().encodeToString(JSON.toJson(pinned).getBytes(UTF_8));
        return "esc_signup=" + payload + "." + sign(payload) + "; Path=/; HttpOnly; SameSite=Lax" + (LIVE ? "; Secure" : "");
    }

    static Pinned pinned(HttpExchange exchange) throws GeneralSecurityException {
        for (String header : exchange.getRequestHeaders().getOrDefault("Cookie", List.of())) {
            Matcher cookie = Pattern.compile("(?:^|; ?)esc_signup=([\\w-]+)\\.([0-9a-f]+)").matcher(header);
            // MessageDigest.isEqual compares in constant time. A cookie that fails is the same as no cookie.
            if (cookie.find() && MessageDigest.isEqual(sign(cookie.group(1)).getBytes(UTF_8), cookie.group(2).getBytes(UTF_8))) {
                return JSON.fromJson(new String(Base64.getUrlDecoder().decode(cookie.group(1)), UTF_8), Pinned.class);
            }
        }
        return new Pinned(null, List.of());
    }

    static void send(HttpExchange exchange, int status, String contentType, String body) throws IOException {
        byte[] bytes = body.getBytes(UTF_8);
        exchange.getResponseHeaders().set("Content-Type", contentType);
        exchange.sendResponseHeaders(status, bytes.length);
        exchange.getResponseBody().write(bytes);
    }

    static void json(HttpExchange exchange, int status, Object body) throws IOException {
        send(exchange, status, "application/json", JSON.toJson(body));
    }

    // The document pages: each one renders a registered version, unmodified.
    static void legal(HttpExchange exchange, String slug) throws Exception {
        Matcher v = Pattern.compile("(?:^|&)v=(\\w+)").matcher(String.valueOf(exchange.getRequestURI().getQuery()));
        Answer<Content> content = esc("GET", "/documents/" + DOCUMENTS.get(slug) + "/versions/" + (v.find() ? v.group(1) : "current") + "/content", null, null, Content.class);
        if (content.status() != 200) {
            json(exchange, 404, Map.of("error", "not_found"));
            return;
        }
        // The JDK has no function that escapes HTML, so the version ID, which goes into an attribute, is checked instead.
        String versionId = content.body().versionId();
        if (!versionId.matches("\\w+")) throw new IllegalStateException("Unexpected version ID");
        // Concatenation escapes nothing: the document HTML is printed as it is.
        send(exchange, 200, "text/html; charset=utf-8",
            "<!doctype html><meta charset=\"utf-8\"><article data-esc-document=\"" + versionId + "\">" + content.body().html() + "</article>");
    }

    // Step 4: create the session with the secret key. The browser gets the client token only.
    static void ceremony(HttpExchange exchange) throws Exception {
        // The page that runs the ceremony: the origin the browser reports, or the Host header of the request.
        String origin = exchange.getRequestHeaders().getFirst("Origin");
        if (origin == null) origin = "http://" + exchange.getRequestHeaders().getFirst("Host");
        Answer<Session> created = esc("POST", "/sessions", Map.of(
            "profile", PROFILE,
            "signer", SIGNER,
            "documents", List.of(
                Map.of("document", DOCUMENTS.get("terms"), "version", "current"),
                Map.of("document", DOCUMENTS.get("privacy"), "version", "current")),
            "context", Map.of("url", origin + "/signup", "locale", "en-US", "purpose", "account_signup")),
            "signup-" + SIGNER.get("external_id") + "-" + UUID.randomUUID(), Session.class);
        Session session = created.body();
        if (created.status() != 201) {
            json(exchange, 502, Map.of("error", session.error() == null ? "unknown" : session.error().code()));
            return;
        }

        List<String> versionIds = session.documents().stream().map(Doc::versionId).sorted().toList();
        exchange.getResponseHeaders().add("Set-Cookie", pinnedCookie(new Pinned(SIGNER.get("external_id"), versionIds)));
        json(exchange, 200, Map.of("clientToken", session.clientToken(), "apiUrl", session.apiUrl(), "documents", session.documents()));
    }

    // Step 6: confirm the record with the secret key before the account exists.
    static void confirm(HttpExchange exchange) throws Exception {
        String recordId = "missing";
        try {
            Object body = JSON.fromJson(new String(exchange.getRequestBody().readAllBytes(), UTF_8), Map.class);
            if (body instanceof Map<?, ?> map && map.get("recordId") instanceof String id) recordId = id;
        } catch (JsonSyntaxException malformed) {
            // an empty or malformed body is refused below
        }
        Pinned expected = pinned(exchange);
        Answer<Signed> answer = esc("GET", "/records/" + URLEncoder.encode(recordId, UTF_8), null, null, Signed.class);
        Signed record = answer.body();

        boolean confirmed = answer.status() == 200
            && record.status() != null && SEALED.contains(record.status())
            && Boolean.valueOf(LIVE).equals(record.livemode())
            && expected.signerId() != null && record.signer() != null && expected.signerId().equals(record.signer().externalId())
            && record.documents().stream().map(Doc::versionId).sorted().toList().equals(expected.versionIds());

        System.out.println(confirmed ? "confirmed " + record.id() + " (" + record.status() + ")" : "refused");
        if (!confirmed) {
            json(exchange, 409, Map.of("confirmed", false));
            return;
        }
        // Only now create the account, and store record.id() and the receipt with it.
        json(exchange, 200, Map.of("confirmed", true, "recordId", record.id()));
    }

    static void route(HttpExchange exchange) throws Exception {
        String path = exchange.getRequestURI().getPath();
        switch (exchange.getRequestMethod() + " " + path) {
            case "GET /signup" -> send(exchange, 200, "text/html; charset=utf-8", Files.readString(Path.of("public", "signup.html")));
            case "GET /legal/terms", "GET /legal/privacy" -> legal(exchange, path.substring("/legal/".length()));
            case "POST /api/ceremony" -> ceremony(exchange);
            case "POST /api/signup/confirm" -> confirm(exchange);
            default -> json(exchange, 404, Map.of("error", "not_found"));
        }
    }

    public static void main(String[] args) throws IOException {
        HttpServer server = HttpServer.create(new InetSocketAddress(Integer.parseInt(env("PORT", "8000"))), 0);
        // The default executor handles every request on one thread. With a virtual thread for each, a call that waits holds only its own request.
        server.setExecutor(Executors.newVirtualThreadPerTaskExecutor());
        server.createContext("/", exchange -> {
            try {
                route(exchange);
            } catch (Exception error) {
                // Without this the server closes the connection with no answer and prints nothing.
                System.err.println(error);
                if (exchange.getResponseCode() == -1) json(exchange, 500, Map.of("error", "internal_error"));
            } finally {
                exchange.close();
            }
        });
        server.start();
        System.out.println("http://localhost:" + server.getAddress().getPort() + "/signup");
    }
}
```

The signer is a fixed test person here. In your app it is the signed-in user or the account you are about to create.

Seven things here are specific to plain Java, and each one was seen in the test run.

The client is pinned to HTTP/1.1. The JDK's client prefers HTTP/2, and over plain http it asks for it with every request: the request it sent carried `Upgrade: h2c` and `HTTP2-Settings`. A server that ignored those headers answered in HTTP/1.1 and all was well. The test API on this machine, which runs over plain http, closed the connection instead, and `send` threw `IOException: HTTP/1.1 header parser received no bytes`. With `HTTP_1_1` pinned the same call was answered `200`. The page keeps the pin because that is the code that was run. Calls over https, where HTTP/2 is agreed in the TLS handshake, were not run.

Every request has a timeout. The JDK's documentation says a request without one blocks forever, and in a test against a server that accepts a request and never answers, a call without `timeout()` was still waiting when the test stopped looking after 4 seconds. With `timeout(Duration.ofSeconds(2))` it threw `HttpTimeoutException` after 2.00 seconds, and the server had received it once. The client does not throw on a refusal: a made-up record ID came back as status `404`.

The JSON is read into records. With `LOWER_CASE_WITH_UNDERSCORES`, Gson filled `clientToken` from `client_token`. With a plain `new Gson()` the same record came back with `null` in every field and no error. `livemode` is a `Boolean`, not a `boolean`: an error envelope read into a record with a `boolean` field gave `livemode=false`, which is exactly what a test deployment expects. With `Boolean` it gave `null`, and the check fails. `Set.of(...).contains(null)` threw a `NullPointerException`, so the status is checked for `null` first.

The state is a cookie the app signs, because plain Java has no session. The browser got a cookie named `esc_signup`, 189 characters long, `HttpOnly` and `SameSite=Lax`. It is signed, not encrypted: decoded from Base64, the part before the dot showed the signer ID and the two version IDs. The visitor can read them and cannot change them. With one character of the signature changed, with the signature cut to 10 characters, and with another signer ID in the payload, the confirm route answered `409`. `MessageDigest.isEqual` compares in constant time and returned `false` for arrays of different lengths. With `COOKIE_SECRET` fixed, the same cookie confirmed a real record after a restart.

The server gets an executor. The JDK's documentation says that without one, requests are handled on the thread that `start()` created. When the API answers `429`, `esc` waits for the seconds in `Retry-After`, 1 at least and 5 at most, and sends the request again, up to twice. In a copy of the app without the `setExecutor` line, page requests sent while four confirmations were in flight waited up to 1.2 seconds behind a call that was waiting to retry. With a virtual thread for each request they were answered in under 0.01 seconds.

The handler catches what the routes throw. In a test with a handler that threw, the server closed the connection with no answer, `curl` reported an empty reply, and nothing was printed. With the `catch`, and the API address on a closed port, the session route answered `500` with `{"error":"internal_error"}`, the log showed `java.net.ConnectException`, and the next request was answered `200`.

The variables are read when the class loads, and a missing one stops the app. With `.env` not loaded it ended with `IllegalStateException: Set the environment variable ESIGNCOMPLY_API_KEY`, inside an `ExceptionInInitializerError`. So did a key that was set and empty.

`context.url` is built from the `Origin` header the browser sends with the `POST`, and from the `Host` header when there is none. Both come from the client. A request with `Origin: https://evil.example` was refused by the API with `domain_mismatch`, and the route answered `502`. So was a request with `Host: evil.example` and no `Origin`.

Start the app from the shell that loaded `.env`. The JDK compiles the file in memory and runs it:

```bash
java -cp lib/gson-2.15.0.jar App.java
```

```text
http://localhost:8000/signup
```

The server listens on every interface of the machine: in the test the page answered on the machine's own address too, not only on `localhost`.

## Step 5. Attach the ceremony in the browser

The browser SDK renders nothing. It observes the checkbox, the notice, the links and the button you built, and reports each step from the signer's browser straight to Esign Comply. Save the page as `public/signup.html`:

```html file="public/signup.html"
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Create account</title>
    <style>
      body { font: 16px/1.5 system-ui, sans-serif; max-width: 480px; margin: 48px auto; padding: 0 20px; }
      a { color: #0b57d0; text-decoration: underline; }
      button { font: inherit; padding: 10px 16px; }
    </style>
  </head>
  <body>
    <h1>Create account</h1>
    <form id="signup">
      <div id="assent">
        <!-- The page is on screen before the script has a session, so the box stays disabled until the SDK watches it. -->
        <label><input id="agree" type="checkbox" disabled /> I agree to the Terms of Service and Privacy Notice</label>
        <p>
          By checking the box and clicking Create account, you agree to the
          <a id="tos-link" href="/legal/terms">Terms of Service</a> and acknowledge the
          <a id="privacy-link" href="/legal/privacy">Privacy Notice</a>.
        </p>
        <button id="create-account" type="submit" disabled>Create account</button>
      </div>
      <p id="message" role="alert"></p>
    </form>

    <script src="https://esigncomply.com/sdk/v1/esigncomply.js"></script>
    <script type="module">
      const agree = document.querySelector("#agree");
      const submit = document.querySelector("#create-account");
      const message = document.querySelector("#message");

      // Your server creates the session and returns only the client token and the pinned documents.
      const response = await fetch("/api/ceremony", { method: "POST" });
      const { clientToken, apiUrl, documents } = await response.json();

      const ceremony = await EsignComply.attach({ clientToken, apiUrl });
      ceremony.on("change", ({ remainingSteps }) => {
        submit.disabled = remainingSteps.some((step) => step !== "signature.applied");
      });

      // Point each link at the exact version this session pinned, then report it.
      const links = [document.querySelector("#tos-link"), document.querySelector("#privacy-link")];
      for (const [i, link] of links.entries()) {
        link.search = "?v=" + documents[i].version_id;
        await ceremony.presentDocument({ versionId: documents[i].version_id, mode: "hyperlink", link });
      }
      await ceremony.observeAssent({
        region: document.querySelector("#assent"), // notice, links, checkbox, button
        checkbox: agree,
        submit,
      });
      agree.disabled = false; // the SDK watches the box from here on. Only the user ticks it.

      document.querySelector("#signup").addEventListener("submit", async (event) => {
        event.preventDefault();
        try {
          const result = await ceremony.complete(); // the signing act, from the signer's own click
          // The result came to the browser. Your server confirms the record before anything is granted.
          const confirmed = await fetch("/api/signup/confirm", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ recordId: result.recordId }),
          });
          message.textContent = confirmed.ok
            ? `Account created. Record ${result.recordId}`
            : "We could not confirm whether your acceptance was recorded. Please wait while we check.";
        } catch (error) {
          message.textContent = error.message;
        }
      });
    </script>
  </body>
</html>
```

Open [http://localhost:8000/signup](http://localhost:8000/signup). The button stays disabled until the box is ticked. Tick it, click **Create account**, and the page shows:

```text
Account created. Record rec_o8aA9ed9bFwEnXY0o3KK
```

The checkbox starts unchecked and disabled. The page is on screen before the script has a session, and the script enables the box once the SDK observes it: a box ticked before that fails [CR-01](https://esigncomply.com/docs/conformance.md#cr-01). In a test with the session request held back, a click on the box did nothing. One page load sent one `POST /api/ceremony`.

Each link opens a document page on your own server that renders the registered version. `legal` builds that page by joining strings, which escapes nothing: the document arrives as it is, which is what this page needs. The JDK has no function that escapes HTML, so the version ID, which goes into an attribute, is checked against `\w+` instead. In a test with the document's `<`, `>` and `&` replaced by hand, the page showed the tags as text and the SDK reported a finding for [CR-08](https://esigncomply.com/docs/conformance.md#cr-08) at Block level: the page behind the link did not match the registered version.

## Step 6. Confirm the record on the server

The result of `complete()` was delivered to the browser, so your server does not trust it. `confirm` in `App.java` reads the record with the secret key and grants access only when four things hold: the status is `recorded`, `timestamped` or `anchored`; `livemode` is what this deployment expects; the signer is the one in the signed cookie; and the document versions are exactly the ones this server pinned there. This step is never optional.

The app prints one line for each confirmation:

```text
confirmed rec_o8aA9ed9bFwEnXY0o3KK (recorded)
```

A record ID that was made up is refused with status `409`. So is a real record ID sent without the cookie, a body that is not JSON, and an empty body:

```bash
curl -s -X POST http://localhost:8000/api/signup/confirm \
  -H "Content-Type: application/json" -d '{"recordId":"rec_made_up"}'
```

```json
{"confirmed":false}
```

See [Server confirmation](https://esigncomply.com/docs/guides/server-confirmation.md) for the webhook that backs this route up when the browser closes early.

## Step 7. Check the result

Open the dashboard and choose **Records**. The test record is there with what was observed, what was asserted, and its evidence report, watermarked TEST.

Then run the conformance check against the page. It opens the page in headless Chromium at three window sizes, signs as a visitor would, and tries four things that must be refused. One of them posts a made-up record ID to your confirm route. The checker is a Node.js command line tool, so it needs Node.js 20.19 or later, in a folder of its own:

```bash
mkdir -p esc-check && cd esc-check
npm init -y && npm install esigncomply playwright
npx playwright install chromium
npx esigncomply check --url http://localhost:8000/signup --callback http://localhost:8000/api/signup/confirm
```

The report for this page's code, shortened:

```text
Violations that must be refused
  REFUSED   Submit with the checkbox untouched      No record was made.
  REFUSED   Completion from another origin          The API answered 403 domain_mismatch.
  REFUSED   Programmatic click                      No record was made.
  REFUSED   Forged success posted to your callback  http://localhost:8000/api/signup/confirm answered 409.

Ceremonies
  390x844    record rec_WckdFhWxxcqukrRT6Tt8  session ses_G3x8p4KH5Vrt6kcsbMDU, 5 events
  768x1024   record rec_QbkHKMMHEhmtkVk6H0tx  session ses_TGCZtYAAWAxEuTQY8go8, 5 events
  1440x900   record rec_xZmwoAuNm2DByYGJkCK8  session ses_PyjcZ8aZvHQVpRpfKPgM, 5 events

Summary: 0 block, 0 warn, 27 pass.
```

The app printed a `confirmed` line for each of the three records.

Fix every finding marked `block` and read every finding marked `warn`. Each one names the rule the screen missed, the measurement and the fix. In test mode a finding never stops a record from being sealed, so read the report. The rules are on [Conformance rules](https://esigncomply.com/docs/conformance.md), and every flag of the command is on the [CLI page](https://esigncomply.com/docs/sdk/cli.md).

## Step 8. Go live

Going live takes three steps on the Esign Comply side. There is no plan to choose and no checkout: the Free plan records 10 live signatures a month.

1. Register your production domain and verify it. See [Register a domain](https://esigncomply.com/docs/guides/domains.md).
2. Add your organization's legal name, country and address under **Go live** in the dashboard.
3. Create a live key. It is shown once and starts with `esc_live_`.

Test and live share nothing, so create the documents and the profile again with the live key, or copy them to live from the dashboard, and use the live IDs in production.

Then switch the server over:

- Compile once with `javac -cp lib/gson-2.15.0.jar -d out App.java` and start it with `java -cp out:lib/gson-2.15.0.jar App`. In the test this ran the app from the compiled classes, and it recorded the signature shown in step 5.
- Start it in the project folder. `public/signup.html` is read relative to the working directory: started from `/tmp`, the app answered `/signup` with `500` and logged `NoSuchFileException: public/signup.html`.
- Set the live key as `ESIGNCOMPLY_API_KEY` and set `ESIGNCOMPLY_LIVE=true` in production only. In the test with that variable set, the confirm route refused a test record with `409`, and the cookie was marked `Secure`. The app adds `Secure` itself and does not look at the request: serve the site over HTTPS.
- Set `PORT` when your host gives you one. The app listens on 8000 otherwise.
- Keep one `COOKIE_SECRET` for every instance and every restart, and store the record ID and the receipt beside the user.

In live mode `context.url` must be inside your registered domain, and browser calls are accepted only from it. By default a live signature with a finding at Block level is recorded and you are told at once which rule failed. Turn on blocking, on the dashboard's Conformance page, and it is refused before it is sealed. Run the check from step 7 until no finding is at Block level before you switch keys.

## Troubleshooting

- **`IllegalStateException: Set the environment variable ESIGNCOMPLY_API_KEY` when the app starts.** The variables are not in the environment of the shell that starts Java. Run `set -a; . ./.env; set +a` in that shell first.
- **`IOException: HTTP/1.1 header parser received no bytes`.** The client is not pinned to HTTP/1.1 and the address is plain http, such as a stand-in for the API in a test. The JDK's client then asks the server to upgrade to HTTP/2, and a server that closes the connection on that request gives this error. Keep `version(HttpClient.Version.HTTP_1_1)` on the client.
- **`domain_mismatch` from `/api/ceremony`.** `context.url` is built from the `Origin` or `Host` header, and that host is not on the test allowlist. Test keys work on `localhost` and `127.0.0.1` at any port. Add other hosts under Domains in the dashboard. See [`domain_mismatch`](https://esigncomply.com/docs/api/errors.md#domain_mismatch).
- **`429` when the confirm route reads the record.** `esc` waits for the seconds in `Retry-After`, 1 at least and 5 at most, and sends the request again, up to twice. Nothing else is retried. In the test, four confirmations sent at once from the session that signed all answered `200`. The API's log showed why: two reads got `429` and passed on the next attempt. See [`rate_limit_exceeded`](https://esigncomply.com/docs/api/errors.md#rate_limit_exceeded). When the route answers `409` for a real record, the cause is a `COOKIE_SECRET` that changed.

## Questions about the Java quickstart

### Is there a Maven artifact for Esign Comply?

No. The server SDK exists for Node.js only. A Java server calls the REST API directly, and this quickstart does it with `java.net.http.HttpClient` in one method. The only jar beside the JDK is Gson, for the JSON.

### Does the quickstart need Maven or Gradle?

No. It was run with the JDK alone: one source file, one jar downloaded from Maven Central, and the `java` command, which compiles a source file in memory. In a project that has a build, add the Gson dependency there and keep the code as it is.

### Which Java version does the code need?

Java 21 or later. It was run on Java 25 only. The code gives each request a virtual thread, and the JDK documentation dates that executor to Java 21.

### Can the visitor read the cookie?

Yes, and that is safe. The cookie is signed, not encrypted: decoded from Base64 it showed the signer ID and the two version IDs, and nothing else is in it. The visitor cannot change it. In the test a cookie with a changed signature or a changed payload was refused with status 409.

### When is the Spring Boot quickstart the better start?

When your app already runs on Spring Boot. It brings a session, JSON binding and Tomcat, and its quickstart uses them. This page is for a service with no framework, where the JDK's own client and server are enough and one jar is all you want to add.

### Does the Java quickstart need a domain or a card?

No. Test mode works on `localhost` with a test key, no card and no domain. You register and verify a domain only when you go live, and the Free plan then records 10 live signatures a month.

## Next steps

- [E-signatures and clickwrap for Java](https://esigncomply.com/java): what the integration gives you on this stack, with the things to watch for.
- [Add e-signatures and clickwrap with Spring Boot](https://esigncomply.com/docs/quickstart/spring-boot.md): the same calls with `RestClient`, Jackson and the `HttpSession`.
- [Server confirmation](https://esigncomply.com/docs/guides/server-confirmation.md): the checks in step 6 and the `record.completed` webhook.
- [Sessions API](https://esigncomply.com/docs/api/sessions.md) and [Records API](https://esigncomply.com/docs/api/records.md): every field of the two calls this app makes.
- [All quickstarts](https://esigncomply.com/docs/quickstart.md#quickstarts-by-stack-and-platform).
