How to handle the double request

with Ajax and Spring Boot

Adrian Adendrata
DOKU Insight
2 min readFeb 27, 2019

--

For some developers, double form submit could be a nightmare if we don’t handle it wisely, especially, if you are a developer in a financial company. Of course, as a Developer, I don’t want this to happen and my boss calls me at night to fix it.

Before that unpleasant thing happens. Here my two techniques to prevent it
1. Disable submit button
2. Issue request token/id

source: https://unsplash.com/collections/4255669/software-development

Disable Submit Button

We can disable submit button right before our function call HTTP request and enable it again after finish gets HTTP response. This technique is effective for the process that takes a long time to finish (more than 5 sec.). The user can not click n’ click again because of impatience to get the result. Additionally, we may show a loading box for a good experience.

example with ajax

as we can see, I add a new function to disable-enable button at beforeSend and complete section.

Issue Requet Token or Id

This technique actually more complicated and difficult to implement, but thanks to a good framework (such as Spring Boot) to make this easier. Before we are going to the code implementation, let’s talk about the mechanism first;

  1. When form page is loaded, issue a new requestId
  2. put issued requestId to HTTP header before calling the backend service
  3. backend service identify a requestId is already registered or not
  4. if requestId is already registered then we can mark as a violation request

Let’s begin the code. Here the example code in my JavaScript to issue a new requestId.

issue new requestId every time page is loaded

Here the example code in my Spring Boot project, I create an Interceptor to handle the requestId

Class to handle the requestId
additionally, we can add Exception Handler

In this example, I am using an in-application memory to store the requestId. For serious development, I recommend using the in-memory database, such as Redis.

Actually, we can modify how to issue a new token and the logic when identifying a requestId. Because the process is very simple, we need something (requestId) to identify that thing is already requested or not.

I hope this tutorial could save your night and make your sleep better :) Thanks…

--

--