Implement Custom Apps
We will implement a custom app to greet users based on a configured greeting word and their name provided as a query parameter.
The site will be located on a configured location.
Apps with multiple sites may offer configuration for each location separately or, as typically done,
have one base location configured and then use location.appendPath("/subpath")
to obtain more specific locations.
// Define app type with type name "greet"
@AppType("greet")
public class GreetingApp extends App {
@Override
public void start() {
AppConfig config = getConfig();
SiteLocation location = config.getLocation("location").orError();
String greeting = config.getString("greeting").orDefault("Hello");
addSite(location, request -> {
String name = request.getQuery("name");
if (name == null)
return new HTTPResponse().setStatus(HTTPStatus.S400_BAD_REQUEST).setContentText("Please provide a name");
// 200 OK status by default, and
// escapeHTML for untrusted input to avoid XSS attacks
return new HTTPResponse().setContentHTML("<h1>" + greeting + ", " + HTTPUtil.escapeHTML(name) + "!</h1>");
});
}
}
With that class anywhere in the servers lib
folder, we can use this app type to configure app definitions.
So if we add a file named welcome.greet.toml
in the apps
directory with the following content:
the server will respond with "Welcome, [name]!" when visiting /welcome?name=[name]
.
In the file name, welcome
is the name of the app and greet
is the type. The extension .toml
indicates that it's a TOML configuration rather than JSON, which is also supported.