How to get submit event timestamp from frontend?

Are you really sure you want to use the client-side timestamp? The problem is that it can lead to weird results in cases when the client’s clock is out of sync. Modern operating systems have NTP enabled by default so this rarely happens by accident but there’s also the possibility of someone maliciously manipulating their clock to exploit the system.

The solution you show doesn’t do what you ask for since it does a separate round trip to fetch the client-side timestamp after the server has already received the original event. Instead, you need to instruct the client-side logic to extract the timestamp when it’s about to send the original submission to the server. To do this, you need to define a subclass of the regular submit event with an additional @EventData expression (the one for value is copied from the super class constructor).

public class TimestampedSubmitEvent extends SubmitEvent {
    private String timestamp;

    public TimestampedSubmitEvent(MessageInput source, boolean fromClient,
            @EventData("event.detail.value") String value,
            @EventData("new Date().toISOString()") String timestamp) {
        super(source, fromClient, value);
        this.timestamp = timestamp;
    }

    public String getTimestamp() {
        return timestamp;
    }
}

And then you need to use ComponentUtil to add a listener for that more specific event instead of the regular submit event.

MessageInput input = new MessageInput();
ComponentUtil.addListener(input, TimestampedSubmitEvent.class, event -> {
    Notification.show(event.getValue() + " @ " + event.getTimestamp());
});
add(input);

If you use the client time only for ordering events, then you don’t need to fetch the time zone since the ISO string is always converted to UTC (which can be seen from the Z at the end of the string).

1 Like