I've been told that in a Spring MVC web application, when we have a Spring MVC Controller with its local variables, it is possible that multiple requests may use the same Spring MVC Controller instance.
Let's assume I have this Spring MVC Controller.
@Controller
@RequestMapping("/test/me/")
public class TestInstantiation {
private String myValue;
@RequestMapping(path = "/try", method = RequestMethod.POST)
@ResponseBody
public String execute(String input, HttpServletRequest req, HttpServletResponse httpResp) throws IOException
{
myValue = input;
//Let's have a lengtly operation here...
httpResp.getWriter().write(myValue);
}
}
If multiple clients send a request to /test/me/try
with different input values, it is possible that one may receive someone's myValue
value.
I am not sure about this claim. I'd appreciate any guidance on that.
CodePudding user response:
You are mixing two different things:
- Java's Web Servlet - that is Java EE (today Jakarta EE)'s web-component, that has long been used to develop web applications in Java - namely, a Java object, that can handle (respond to) HTTP messages;
and
- Spring Framework's
@Controller
component - which is, definitely, under the hood used by Java servlet to handle HTTP messages, but that's not something you should worry about. That was the point of bringing@Controller
s, to simplify the complexity and boiler-plate of vanilla servlets. You don't create servlet out of controller classes. That means, you don't extendHttpServlet
abstract class, with your Spring MVC@Controller
class.
What you were told is probably a point about Dispatcher Servlet
, which is a Spring Web Framework's implementation for Front-Controller design pattern, that's used in MVC applications.
If multiple clients send a request to /test/me/try with different input values, it is possible that one may receive someone's myValue value.
Every request will be processed in a separate thread - so every client can pass their Request Parameters (query string or payload) and those parameters will be passed into different invocations of your handler method.
CodePudding user response:
If I understand your question correctly, your Controller looks singleton but for member variable myValue
you might need to use StringBuffer
(if its allowed) to make it thread safe so that multiple requests can use this member variable without any issue.
Or else, if there is no further use of myValue
in other methods then I would suggest to make myValue
as local to function so that any request will have its own copy of myValue
.