Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unique identifier for a connection in Tomcat

Tags:

java

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 ?

like image 765
Darek Avatar asked Oct 22 '25 22:10

Darek


2 Answers

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.

like image 163
StuPointerException Avatar answered Oct 24 '25 14:10

StuPointerException


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.

like image 25
Christopher Schultz Avatar answered Oct 24 '25 12:10

Christopher Schultz