I have a web application where multiple servlets use a certain amount of identical logic for pre-initialization (setting up logging, session tracking, etc.). What I did was to introduce an intermediary level between javax.servlet.http.HttpServlet
and my concrete servlet class:
public abstract class AbstractHttpServlet extends HttpServlet {
// ... some common things ...
}
and then:
public class MyServlet extends AbstractHttpServlet {
// ... specialized logic ...
}
One of the things I do in AbstractHttpServlet's default (and only) constructor is to set a few private member variables. In this case it is a UUID, which serves as a session identifier:
public abstract class AbstractHttpServlet extends HttpServlet {
private UUID sessionUuid;
public AbstractHttpServlet() {
super();
this.sessionUuid = UUID.randomUUID();
// ... there's more, but snipped for brevity ...
}
protected UUID getSessionUuid() {
return this.sessionUuid;
}
}
I then use getSessionUuid()
in MyServlet
to provide for session tracking within the request. This is very useful e.g. in logging, to be able to sift through a large log file and get all entries relating to a single HTTP request. In principle the session identifier could be anything; I just picked using a UUID because it is easy to generate a random one and there's no need to worry about collisions between different servers, seed issues, searching through the log file turning up a match as a portion of a longer string, etc etc.
I don't see any reason why multiple executions should get the same value in the sessionUuid
member variable, but in practice, it appears that they do. It's as if the instance of the class is being reused for multiple requests even over a long period of time (seemingly until the server process is restarted).
In my case, class instantiation overhead is minor compared to the useful work done by the class, so ideally I'd like Tomcat to always create new class instances for each request and thus force it to execute the constructor separately each time. Is it possible to perhaps annotate the class to ensure that it is instantiated per request? Answers that don't require server configuration changes are much preferred.
Failing that, is there a way (other than doing so separately in each do*() method such as doGet()
, doPost()
, etc.) to ensure that some sort of initialization is done per HTTP request which results in execution of a particular servlet?