可能重复:
ThreadLocal to store ServletRequest and Response in servlet: what for?
我有一个servlet类,它将信息发送到某个Delegator类,后者会调用一些Business Service方法。
我需要当前的HttpServletRequest和HttpServletResponse对象到Delegator类的方法。我没有将它作为方法签名的一部分,而是考虑在servlet类的ThreadLocal变量中设置它,然后在Delegator类的方法中从ThreadLocal变量中检索它。
以下是示例代码。
//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();
}
}
您能否建议这种方法是否存在任何可能的问题?