Is there any way to retrieve a session from a POJO? Or ultimately to retrieve a bean from a POJO.
To clarify:
Basically I am creating a bean from a servlet and I need to access the properties of that bean from outside of the web container (from a POJO). I cannot pass the request to the pojo; and the request is needed to retrieve the session.
More specifically I have a web application that uses the Cactus framework to run JUnit tests from a web interface. However the servlet that invokes the JUnit test runner is compiled in a jar; I added extra drop down menus to change settings from which the JUnit test will read from to switch between different environments (WLI clusters), so given that the runner servlet is already compiled I cannot modify it to handle the extra parameters from the multiple environments. I have tried the persistence approach of writing to a .dat file fro which the JUnit test will read from by way of a Reader class; also I have have tried the bean approach which ultimately was not accessible from the JUnit test.
Only and only if your POJO is running in the same thread as the
HttpServletRequestis running in, then you’ll be able to achieve this with help ofThreadLocal<T>.Create the following class:
Implement
javax.servlet.Filterwhich does the following indoFilter()method and is mapped on anurl-patternof interest, e.g./*or on theservlet-nameof your front controller servlet.Note the importance of try-with-resources statement. It guarantees that the
YourContext#close()will be called after the filter has done its job and theThreadLocalresource will be cleared. Otherwise the thread will still contain it when recycled for another HTTP request.And here’s how you could use it in the POJO:
This all is basically also how the
Contextobjects of the average MVC framework works, like JSF’sFacesContextand the one in Wicket.Said that, have you looked at CDI? Perhaps it’s easier to make the artifacts CDI-managed so you can just
@Injectthem in each other.