1

可能重复:
ThreadLocal 将 ServletRequest 和 Response 存储在 servlet 中:为什么?

我有一个 servlet 类,它将信息发送到某个 Delegator 类,该类稍后调用一些业务服务方法。

我需要 Delegator 类方法的当前 HttpServletRequest 和 HttpServletResponse 对象。我没有将其保留为方法签名的一部分,而是考虑将其设置在 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();
        }

}

您能否建议这种方法是否存在任何可能的问题?

4

0 回答 0