|
|
|
Writing Java handlers
Basic class structure
Java implementation of an event handler must include:
- A no-arg public constructor; the default constructor is fine
- Method implemented with signature of the form:
public void on<eventName>()
For example, an excerpt of zero.core.fileserver.FileServer shows handler logic for GET, POST, PUT, and DELETE events:
public class FileServer {
public void onGET() {
String path = zget("/event/path");
File f = new File(path);
try {
returnFile(f);
} catch (IOException e) {
// FileServer is invoked only after confirming that f exists, so
// an IOException indicates another problem
throw new RuntimeException(e);
}
}
public void onPOST() {
Map<String, Object> headers = new HashMap<String, Object>();
headers.put("Allow", "GET");
ErrorPage.send(HttpURLConnection.HTTP_BAD_METHOD, headers, null);
}
public void onPUT() {
Map<String, Object> headers = new HashMap<String, Object>();
headers.put("Allow", "GET");
ErrorPage.send(HttpURLConnection.HTTP_BAD_METHOD, headers, null);
}
public void onDELETE() {
Map<String, Object> headers = new HashMap<String, Object>();
headers.put("Allow", "GET");
ErrorPage.send(HttpURLConnection.HTTP_BAD_METHOD, headers, null);
}
}
Exceptions
Handlers can throw an Exception to indicate an internal error. Details about exception handling are described in the Event processing section.
|