In most modern web development, the priority is user experience. You can have great back-end code, however if the interface feels sluggish or not responsive enough, users will become very frustrated. When developing with popular front-end frameworks and libraries (ReactJS, Angualr, etc), any interaction with the back-end server needs to be as fast as possible and asynchronous.
A common approach to handle this is creating HTTP endpoints that accept parameters and return only the information needed to update the UI. Typically the response will contain JSON data, so let’s look at a simple way to implement this in Wicket.
Creating a JSON response WebPage
The first thing we need to do is create a base class that all of our endpoint pages will extend:
public abstract class JsonResponsePage extends WebPage {
public JsonResponsePage(final PageParameters pp) {
super(pp);
getRequestCycle().scheduleRequestHandlerAfterCurrent(new TextRequestHandler("application/json", "UTF-8", sendResponse(pp)));
}
@Override
public MarkupType getMarkupType() {
return new MarkupType("html","application/json");
}
protected abstract String sendResponse(final PageParameters pp);
}
Believe it or not this is the bulk of the code that is needed! We override getMarkupType() to indicate the correct response type to the browser because it won’t be returning HTML content like in a regular Wicket WebPage.
The sendResponse() accepts HTTP GET/POST parameters and returns a string with the JSON response. Individual WebPages that extend our class will have their own implementations of this method.
A simple endpoint implementation
Let’s implement a simple “tweet” endpoint. Imagine the page has a form with a textarea allowing the user to tweet messages. Here’s how we might implement it:
public class TweetEndpoint extends JsonResponsePage {
public TweetEndpoint(final PageParameters pp) {
super(pp);
}
@Override
protected String sendResponse(PageParameters pp) {
IRequestParameters reqParams = getRequest().getRequestParameters();
String tweetTxt = reqParams.getParameterValue("tweet").toString();
Integer currUserId = userService.getCurrentUserId();
Tweet insertedTweet = tweetService.createTweet(currUserId, tweetTxt);
JSONObject json = new JSONObject();
try {
json.put("status", "SUCCESS");
json.put("tweet_id", insertedTweet.getId());
} catch (JSONException e) {
}
return json.toString();
}
}
We get the text to tweet from the request parameters, and using the current logged-in user ID, we create a new Tweet. We then send back a JSON response indicating the operation succeeded and the ID of the newly created tweet.
Using our endpoint from Javascript
Now you might be wondering how to send a request to our tweet endpoint from the front-end. It’s straightforward and consists of two steps. The first thing we need to do is to get the URL of our endpoint into a JS variable. We can do that by overriding the renderHead() method in our WebPage:
@Override
public void renderHead(IHeaderResponse response) {
super.renderHead(response);
String endpointUrl = (String) urlFor(DropdownSuggestionsPage.class, new PageParameters());
response.render(JavaScriptHeaderItem.forScript("tweet_endpoint = '"+endpointUrl+"'; ", "tweet_endpoint"));
}
Now all we have to do is send a request to the endpoint. We might do it this way using the fetch API:
fetch(tweet_endpoint, { method: 'post', body: body: JSON.stringify(data) })
.then(function (data) {
console.log('Tweet saved with JSON response', data);
})
.catch(function (error) {
console.log('Request failed', error);
});
Helper methods
Lastly, we can also define some helper methods in our JsonResponsePage base class to avoid some boilerplate code in our endpoints. Here is a helper method that can send back a simple JSON response containing a status code and message:
protected String sendResponse(String statusCode, String msg) {
JSONObject json = new JSONObject();
try {
json.put("status", statusCode);
json.put("msg", msg);
} catch (JSONException e) { }
return json.toString();
}
And here is a helper method for retrieving request parameters:
protected String getRequestParam(IRequestParameters reqParams, String name) {
StringValue paramPP = reqParams.getParameterValue(name);
return paramPP == null || paramPP.isEmpty() ? null : paramPP.toString();
}