将 HttpServletResponse 和 HttpServletRequest 存储为 HttpServlet 的两个字段
将 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 ?
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
}
}
or should I invoke something like:
do1(req,resp);
do2(req,resp);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不!
因为 servlet必须是线程安全的。多个线程将同时处理该 servlet 对象。如果将请求/响应存储在字段中,则线程安全性就会消失。
不要仅仅为了避免参数传递带来的视觉上的不愉快而试图采取这种捷径。
如果确实必须避免参数,请将请求/响应存储在 java.lang.ThreadLocal 字段中。这仍然是不好的做法,但至少现在它是线程安全的。
No!
Because servlets must be thread-safe. Multiple threads will be going through that servlet object concurrently. If you store the request/response in fields, your thread-safety goes out of the window.
Don't be tempted to take this kind of shortcut just to avoid the visual unpleasantness of parameter passing.
If you really must avoid parameters, then store the request/response in
java.lang.ThreadLocal
fields. It's still bad practice, but at least now it'll be thread-safe.