4

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 ?

2
  • 1
    Do you really mean connection (i.e. multiple requests on the same connection using HTTP keep-alive get the same ID) or do you mean per HTTP request? Commented Nov 5, 2013 at 23:20
  • They are almost certainly not separate connections, and they almost certainly share the same session. If you want to number individual requests, say so. Commented Dec 11, 2023 at 21:33

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It would also make a lot of sense to put the request-id into the request attributes.
1

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.

1 Comment

Thanks for this, Chris! I was just looking for info about the topic.
0

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.

1 Comment

This is useful, but a new JSESSIONID would need to be generated for "every connection" if it were to be considered as a solution. Is this possible, or does Tomcat provide a file-based session cache by default. Can sessions be turned off while still generating the JSESSIONID?
-1

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.