我正在使用 Spring Web 项目,但我遇到了实例变量的问题,我使用列表来存储报告数据,当用户请求此报告时,我存储此列表以便稍后使用它用于 Excel 生成,但是当另一个用户请求相同的报告时,列表将使用请求的新数据重写,并且当第一个用户下载报告时,它会附带第二个用户请求的数据。
我的类(class):
public class foo{
List<Service> services;
GetMapping({"/Report/Detail"})
String getReport(Parameters params, ModelMap model){
services = new ArrayList<>();
//A lot of stuff
services = serviceRepository(params);
//A lot of stuff
model.addAttribute("services",services)
return "ReportDetail";
}
GetMapping({"/Report/Detail/Excel"})
byte[] getExcelReport(){
//Using the List<services> here to download the report
//this List is getting modified by the second user
byte[] excelReport = excelService(services);
return excelReport;
}
}
我不想做重大改变,因为类太大了,它工作得很完美,但我遇到了这个问题,我正在寻找解决方法。
如有任何建议,我们将不胜感激。
最好!
最佳答案
每次用户向 /Report/Detail
发送请求时,您都会覆盖服务列表。如果您希望每个用户都有自己的列表,那么您必须使用不同的方法。例如,您可以使用存储用户( key 应唯一标识用户)及其各自列表的映射。
Map<UserKey, List<Service>> services;
稍后在方法中通过以下方式获取正确的列表
List<Service> userServices = services.get(userKey);
如果是分布式应用程序,您当然必须使用分布式 map (可能包括 Hazelcast 或 Ehcache)
关于java - 基于 Web 的项目的实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54674606/