• Fat Cats Boardgame
  • Wicket UI Library
  • About Me

Java and Wicket web development thoughts, tutorials, and tips

roman@coderdreams.com
Coder DreamsCoder Dreams
  • Fat Cats Boardgame
  • Wicket UI Library
  • About Me

How to write a JSON response in Wicket

January 26, 2020 Posted by Roman Sery wicket No Comments

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();
	}
No Comments
Share
0

About Roman Sery

I've been a software developer for over 10 years and still loving Java!

You also might be interested in

Wicket-fields UI library v1.0 released!

Aug 28, 2019

Wicket-fields is a UI library that makes creating simple bootstrap UI's a breeze

Happy holidays

Dec 24, 2019

Just a short note

How to add a data access layer to your Wicket app using Hibernate and Spring JPA with minimal code

Dec 17, 2019

Learn how to quickly add database communication to your Wicket app using Hibernate and Spring Data JPA while writing almost no code!

Categories

  • aws
  • customization
  • database
  • debugging
  • enum
  • java
  • models
  • performance
  • projects
  • react
  • software design
  • Spring
  • tool
  • Uncategorized
  • wicket

Recent Posts

  • Rent Day
  • Self-contained Wicket Fragments
  • Pros and cons of unit testing
  • Themeable React Monopoly board
  • Please dont use client-specific release branches

Recent Comments

  • TCI Express Thanks for sharing such insightful information. TCI Express truly stands out as the best air logistics company, offering fast, secure, and efficient air express and cold chain transportation services....

    Tracking down a bug in production Wicket application ·  March 25, 2025

  • Tom Error: A zip file cannot include itself Can you please correct the plugin part so it doesn't use the same folder as input?

    Deploying Spring Boot app to AWS Beanstalk with Nginx customization ·  September 3, 2021

  • Golfman: Reality always wins I've used both Wicket and front-end JS frameworks and, having worked extensively on both, I can tell you that "Speed of development" is definitely NOT with the JS frameworks. You basically end up...

    Five reasons you should use Apache Wicket ·  August 29, 2021

  • Kiriller Sorry can not agree with you, wicket might be a well built technical framework. But the advantages of using a front-end framework like react.js and vue.js can not be beaten by Wicket nowadays. - Speed...

    Five reasons you should use Apache Wicket ·  August 23, 2021

  • Bernd Lauert Sorry but i have to refute your claims with the following arguments: 1. the Wicket community may be small but it is also very responsive, you usually get a helpful answer from the core devs on the...

    Five reasons you should use Apache Wicket ·  July 1, 2021

Archives

  • May 2021
  • October 2020
  • September 2020
  • August 2020
  • July 2020
  • June 2020
  • May 2020
  • April 2020
  • March 2020
  • February 2020
  • January 2020
  • December 2019
  • November 2019
  • October 2019
  • September 2019
  • August 2019
  • July 2019

Contact Me

Send Message
Prev Next