java - 将 HttpServletResponse 和 HttpServletRequest 存储为 HttpServlet 的两个字段

标签 java servlets httprequest httpresponse member

HttpServletRequestHttpServletResponse 临时存储为 HttpServlet 的两个字段(见下文)是否是一种好的做法/安全的做法?如果不是,为什么?

import java.io.IOException;    
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Test extends HttpServlet
    {
    private HttpServletRequest req;
    private HttpServletResponse resp;
    @Override
    protected void doPost(
            HttpServletRequest req,
            HttpServletResponse resp
            )
            throws ServletException, IOException
        {
        try
            {
            this.req=req;
            this.resp=resp;
            do1();
            do2();
            }
        finally
            {
            this.req=null;
            this.resp=null;
            }
        }

    private void do1() throws ServletException, IOException
        {
        //use req resp
        }
    private void do2() throws ServletException, IOException
        {
        //use req resp
        }
    }

或者我应该调用类似的东西:

do1(req,resp);
do2(req,resp);

最佳答案

Is it a good practice/safe to temporarily store the HttpServletRequest and the HttpServletResponse as two fields of a HttpServlet (see below) ?

不!

If not, why ?

因为 servlets 必须是线程安全的。多个线程将同时通过该 servlet 对象。如果您将请求/响应存储在字段中,您的线程安全性就会消失。

不要试图采取这种捷径来避免参数传递的视觉不愉快。

如果您真的必须避免使用参数,则将请求/响应存储在 java.lang.ThreadLocal 字段中。这仍然是不好的做法,但至少现在它是线程安全的。

关于java - 将 HttpServletResponse 和 HttpServletRequest 存储为 HttpServlet 的两个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5309118/

相关文章:

java - Servlet图像显示

javascript - 如何使用ajax将js数组发送到servlet?

java - 使用参数重定向 (POST) 到外部 URL 并在 JSP 上获取其响应

c - 监听多个端口并接受连接

javascript - AngularJS 向 $http.get 添加 header

java - SOAPHandler 到底在什么时候拦截传出消息

Java + 正则表达式 : matching characters from a customized set that are not preceded by characters in the same set

PHP 通过使用使用 http 请求的模块来防止超时

java - java的ConcurrentHashMap对于仅获取映射的优点?

java - jclouds:创建 BlobStoreContext 时如何提供自己的 KeyStore