Darek
Darek

Reputation: 2921

Unique identifier for a connection in Tomcat

I would like to obtain a unique identifier for every connection established to Tomcat. I am not talking about sessions or uniqueness of users (clients) but every connection. Say, client A sends one GET, then another. In my scenario these are two separate and unique connections.

Is there any variable or something that can play identifier role for such a connection in Tomcat ?

Upvotes: 4

Views: 2176

Answers (4)

Christopher Schultz
Christopher Schultz

Reputation: 20882

Jakarta Servlet 6.0 (c. 2022) adds a new method to the ServletRequest interface: getRequestId.

While you may have had to write your own request-id-generator in the past, you should now be able to rely on a container-agnostic feature in your web applications.

Upvotes: 1

pasha701
pasha701

Reputation: 7207

Servlet container has session tracking mechanism, usually its cookie with name "JSESSIONID", you can use it as session identifier. From servlet specification:

The standard name of the session tracking cookie must be JSESSIONID, which must be supported by all 3.0 compliant containers

More details can be found in servlet specification.

Upvotes: 0

StuPointerException
StuPointerException

Reputation: 7267

One option is to use a ServletFilter:

public class UniqueRequestFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res,
                         FilterChain chain) throws IOException, ServletException {

        String requestID = UUID.randomUUID().toString()
        //save to ThreadLocal...

        try {
            chain.doFilter(req, res);
        }
        finally {
            //remove from ThreadLocal
        }
    }


    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }
}

You will be able to get the request value from the ThreadLocal at any point in your application.

Upvotes: 3

Plux
Plux

Reputation: 412

One solution could perhaps be to create a new session on every request?

A way to achieve that would be to set true in session-config/cookie-config in web.xml (unless you are running a HTTPS connection)

Upvotes: -1

Related Questions