lesnar
lesnar

Reputation: 2480

MD5 hashcode using spring for http request

i want to generate unique md5 for every http request that will hit REST API. So far i have just used String requestParameters but actual httpRequest will have many other things. How can i achieve this ?

public final class MD5Generator {

public static String getMd5HashCode(String requestParameters) {
    return DigestUtils.md5DigestAsHex(requestParameters.getBytes());
}

}

My Controller

@RequestMapping(value = { "/dummy" }, method = RequestMethod.GET)
public String processOperation(HttpServletRequest request) {
    serviceLayer = new ServiceLayer(request);
    return "wait operation is executing";
}

Service layer

private String httpRequestToString() {
    String request = "";
    Enumeration<String> requestParameters = httpRequest.getParameterNames();
    while (requestParameters.hasMoreElements()) {
        request += String.valueOf(requestParameters.nextElement());
    }
    if (!request.equalsIgnoreCase(""))
        return request;
    else {
        throw new HTTPException(200);
    }
}

private String getMD5hash() {
    return MD5Generator.getMd5HashCode(httpRequestToString());

}

Upvotes: 0

Views: 2040

Answers (3)

girish mahajan
girish mahajan

Reputation: 79

You can do this but in future maybe. I search and not found automated way to achieve this

@GetMapping("/user/{{md5(us)}}")

Upvotes: 0

Efe Kahraman
Efe Kahraman

Reputation: 1438

You can combine request time (System.currentTimeMillis()) and remote address from HttpServletRequest. However, if you're expecting high loads, multiple requests may arrive from a particular client in the same millisecond. To overcome this situation, you may add a global atomic counter to your String combination.

Once you generate an MD5 key, you can set it in ThreadLocal to reach afterwards.

Upvotes: 1

mzc
mzc

Reputation: 3355

Do you see any issues with generating an UUID for every request and use that instead?

For example, you could generate the UUID and attach it to the request object if you need it during the request life-cycle:

    String uuid = UUID.randomUUID().toString();
    request.setAttribute("request-id", uuid);

Upvotes: 1

Related Questions