【发布时间】:2011-07-13 06:22:39
【问题描述】:
我以为我已经知道变量何时具有值。 但令我惊讶的是,当我在另一个浏览器中打开该变量时,它已经有了一个值。 我猜该值仍然驻留在网络服务器中。我在想,当我将它打开到另一个浏览器甚至另一台计算机时,它会在内存中拥有自己的变量。
我在我的 Servlet 的全局范围内首次出现时声明该变量设置为 null。
List<RecordsInfo> recordsInfo = null;
//with getter and setter;
那我有这样的功能
function exportToExcel(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
String filePath = "";
try {
if(recordsInfo != null){
/*I need to check first if recordsInfo has already value before creating an excel file.
This is to make sure that the records viewed are the same and will not make another query.*/
filePath = excelExporter.generateExcel(recordsInfo); //do something...
request.setAttribute("filePath ",filePath );
getServletContext().getRequestDispatcher("/docs/download.jsp").forward(request, response);
} else {
//so something....
}
} catch (Exception e)
e.printStackTrace();
}
}
下载.jsp (JSTL)
Click <a href="${filePath}">here</a> to download.
我知道我初始化后可以获取recordsInfo的值,所以我在exportToExcel中使用了它。但我的问题是使用相同功能的其他浏览器得到相同的结果,我认为它是空的,因为它有不同的会话。
虽然我已经计划解决这个问题,但我只是想从专家那里得到一些建议。
我的问题是什么时候变量死亡(当 Java 垃圾收集器处理它时) 以及为每个会话声明唯一的变量的最佳实践是什么。 我希望我把我的问题说清楚了。我会很感激任何帮助。谢谢!
【问题讨论】:
标签: java jsp servlets jakarta-ee scope