简体   繁体   English

Spring MVC Singleton Controller-多个下载请求

[英]Spring MVC Singleton Controller - Multiple Download Requests

I'm aware that Spring MVC controllers are Singletons. 我知道Spring MVC控制器是Singletons。

So, using the controller's fields to store data can result into security issues. 因此,使用控制器的字段存储数据可能会导致安全问题。

What by question is, suppose it have a mapping which allows users to download a file - 问题在于,假设它具有允许用户下载文件的映射-

@RequestMapping(value = "downloadReport", method=RequestMethod.GET)
public void downloadReport(@RequestParam("reportStoreId") String reportStoreId,
            HttpServletResponse response, HttpServletRequest request) {
    // use reportStoreId to fetch a report from file system and pass it to user using PrintWriter, response.getWriter(), etc...
}

so if multiple users request to download files with different IDs at the same time, could it lead to one user getting a file requested by another user ? 因此,如果多个用户请求同时下载具有不同ID的文件,是否可能导致一个用户获得另一用户请求的文件?

If your implementation of downloadReport is Thread Safe , then you do not have to worry about this. 如果您对downloadReport的实现是Thread Safe ,那么您不必为此担心。

In the situation you describe, multiple threads will be executing downloadReport . 在您描述的情况下,多个线程将执行downloadReport If all of the variables used in the execution are on each thread's stack, they won't collide. 如果执行中使用的所有变量都在每个线程的堆栈上,则它们不会冲突。 Here is a simple example to illustrate: 这是一个简单的例子来说明:

@RequestMapping(value = "downloadReport", method=RequestMethod.GET)
public void downloadReport(@RequestParam("reportStoreId") String reportStoreId,
            HttpServletResponse response, HttpServletRequest request) {
    response.getWriter().print(getReportText(reportStoreId));
}

You would need to implement getReportText to return the text of the named report -- or something similar. 您将需要实现getReportText以返回命名报表的文本-或类似的东西。 As you can see, getReportText returns the text according to its parameter. 如您所见, getReportText根据其参数返回文本。 This parameter is on the thread's call stack and will be different for each request (unless, of course, the two request are for the same file). 此参数在线程的调用堆栈上,并且对于每个请求都将有所不同(当然,除非两个请求都针对同一文件)。

The short answer is no. 最简洁的答案是不。

Not so short answer follows. 答案不是那么简短。 For each request spring will invoke method of the controller and will pass its own value of id parsed from HTTP request. 对于每个请求,spring将调用控制器的方法,并将传递其自己的从HTTP请求解析的id值。 The stack variable is very different from class field. 堆栈变量与类字段有很大不同。 It's lifecycle is different, it is created when method starts and is destroyed when method finishes. 它的生命周期不同,它是在方法启动时创建的,并在方法完成时销毁的。 Also it is not accessible by other concurrently running threads so no interference may happen. 而且其他并发运行的线程也无法访问它,因此不会发生干扰。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM