【发布时间】:2018-01-13 13:43:11
【问题描述】:
这是示例代码,说明了实例变量和请求属性的用法:
@WebServlet(name = "Upload", urlPatterns = {"/upload"})
@MultipartConfig()
public class Upload extends HttpServlet {
private String txt;
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try{
String txt2 = (String) request.getAttribute("txt2");
//txt and txt2 variables are available for processing.
..........
} finally {
txt = null;//Prepare variable for next request.
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
.....
request.setAttribute("txt2", someValue);
//vs
txt = someValue;
processRequest(request, response);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
.....
processRequest(request, response);
}
}
现在我知道实例变量不应该在 servlet 中声明,因为在并发请求之间共享同一个 servlet。但是请求属性呢?使用它们安全吗?
【问题讨论】:
-
不确定您到底想要什么,但请记住所有请求共享同一个 servlet 对象,因此您不能使用私有字段,除非您希望该字段在所有正在运行的 servlet 之间共享。 (你没有)
-
你的意思是,如果我在 servlet 代码中声明像 private String str; 这样的变量,多个并发会话可以访问它?
-
是的,正是.......
-
所以这是一个非常严重的问题,并且明确地回答了我的问题..
-
请求是唯一的。 Ergo 它的请求属性集合也是如此。 Ergo 它们是线程安全的。
标签: java performance servlets