Possible Duplicate:
ThreadLocal to store ServletRequest and Response in servlet: what for?
I have a servlet class which sends information to some Delegator class which later invokes some Business Service methods.
I need the current HttpServletRequest and HttpServletResponse objects to the Delegator class's methods. Instead of keeping it as part of the method signature, I thought about setting that in a ThreadLocal variable from servlet class and later retrieving it from the ThreadLocal variable in Delegator class's methods.
Below is the sample code.
//Servlet class
public class TestServlet extends HttpServlet{
protected void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException,IOException{
Utils.setHttpServletRequest(request);
Utils.setHttpServletResponse(response);
}
}
//******Utils class*************
public class Utils {
public static final ThreadLocal<HttpServletRequest> servletRequest = new ThreadLocal<HttpServletRequest>();
public static final ThreadLocal<HttpServletResponse> servletResponse = new ThreadLocal<HttpServletResponse>();
public static HttpServletRequest getHttpServletRequest(){
return servletRequest.get();
}
public static HttpServletResponse getHttpServletResponse(){
return servletResponse.get();
}
public static void setHttpServletRequest( HttpServletRequest request ){
servletRequest.set( request );
}
public static void setHttpServletResponse( HttpServletResponse response ){
servletResponse.set( response );
}
}
//Delegator clas
public class TestClass{
public void testMethod(){
//IS THIS CORRECT?
HttpServletRequest request=Utils.getHttpServletRequest();
}
}
Could you please suggest if there can be any possible issues with this approach?