将 HttpServletRequest 和 HttpServletResponse 临时存储为 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/