I have a login function.I want my function not work for example 10 seconds if the user call it for more than 5 time.what should i do for that?I will be glad if some one answer my question.
You need to record failed login attempts for a user (e.g. in database) and once it reaches the threshold, you need to return error response from login method for configurable amount of time from the last failed login attempt, e.g.:
x minutes from that timestampfunction not work for example 10 seconds
You need to be specific on what exactly you mean by function not to work. But if you simply wanted to block the method call for x seconds, follow the below approach:
You need to create a counter to count the number of attempts and then if(counter>5) then use Thread.sleep(10000) to make the request to hold (sleep) for 10 seconds. Ideally, the counter value should be persisted to a database (or any other storage) and read it again to validate the number of attempts.
But, I strongly suggest you follow @Darshan's answer which makes more sense.
First you need to identify the user .
This can be done on the basis of IP .
Have a ConcurrentHashMap
ConcurrentHashMap<String,Long>IpAddressValidationMap // String is the Ip address and Long is the timeInMilleseconds
You make a filter and put a check
public void prefilterFunction(RequestObject object)
{
String ip=object.getIP(); // just an example not the standard call for getting Ip addr
Long time=IpAddressValidationMap.get(ip);
if(time!=null)
{
if(time<THRESHOLD_TIME)
{
return ;
}
else
{
// We allow the user to proceed
}
}
}
public void validateLogin(RequestObject object)
{
// if the login fails
IpAddressValidationMap.put(ipAddr,System.currentTimeinMIllis());
}