Writing Java handlers
Java™ can be used to implement handlers within IBM® WebSphere® sMash applications.
Basic class structure
Java implementation of an event handler must include the following elements:
- A no-arg public constructor; the default constructor is fine
- Method implemented with signature of the form:
public void on<eventName>()
For example, the following 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 provided in the Event processing article.