Because spring MVC is singleton by default, it creates a potential security risk. The fundamental core is the problem of the instance variable holding state. This means that each request comes in and the system is processed using the original instance, which results in two outcomes:
One is that we don't have to create a controller every time,
The second is to reduce the time of object creation and garbage collection;
Since there is only one controller's instance, when multiple threads call it at the same time, the instance variable inside it is not thread-safe, and the problem of channeling data can occur.
Of course, in most cases, we do not need to consider thread-safety issues, such as Dao,service, unless you declare an instance variable in the bean. Therefore, when we use Spring MVC's contrller, we should avoid defining instance variables in the controller.
Such as:
public class Controller extends Abstractcommandcontroller {
......
Protected Modelandview handle (httpservletrequest request,httpservletresponse response,
Object command,bindexception Errors) throws Exception {
Company = ..........;
}
Protected company Company;
}
There is a tag company here that has a concurrency thread safety problem.
If the controller is in a singleton form, and there is a private variable A in it, all requests to the same controller, the A variable used is common, that is, if the variable A is modified in a request, the content of the modification can be read in the other request.
There are several workarounds:
1. Do not use instance variables in the controller
2. Change the scope of the controller from Singleton to prototype, i.e. declare scope= "prototype" in the Spring Config file controller and create a new controller each time
3. Use the threadlocal variable in the controller
These kinds of practices are good and bad, the first, developers need to have a high level of programming and ideological awareness, in the coding process to avoid this bug, and the second is that the container automatically generates an instance of each request, garbage collection by the JVM, so it is thread-safe.
The advantage of using the first method is that the instance object has only one, all requests call the instance object, the speed and performance is better than the second, the bad place, is to need the programmer to control the state of the instance variable to maintain the problem. The second is because each request creates an instance, so it consumes more memory space.
So when you use spring to develop the web, be aware that the default controller, Dao, and service are all singleton.
Thread security issues with spring concurrent access