这可能是一个愚蠢的问题,但我只是感到困惑。
我有一个 Controller ,其中创建了一个对象,并且我想在其他几个 Controller 中使用该对象。
目前我的对象是一个类变量,当发出其他用户请求或 session 请求时,它会被覆盖,我确信这不好并且会产生一些 session 问题。
假设以下是我的场景:
@Controller
public class DemoController
{
/* CURRENTLY THIS IS WHAT I'M DOING BUT I DON'T WANT THIS VARIABLE GLOBAL*/
private MyCommonObject myCommonObject = new MyCommonObject();
@RequestMapping(value="/demo-one", method=RequestMethod.POST)
public ModelAndView postControllerOne(@ModelAttribute SearchForm searchForm,
ModelMap modelMap)
{
//I want to use this object in all other controllers too
myCommonObject = someMethodToGetApiResult(searchForm);
SomeOtherObject someOtherObject = getSomeObject(myCommonObject);
modelMap.addAttribute("someOtherObject",someOtherObject);
return new ModelAndView("/firstJSP");
}
@RequestMapping(value="/demo-two", method=RequestMethod.POST)
public ModelAndView postControllerTwo(@ModelAttribute SomeForm someForm,
ModelMap modelMap)
{
// Used the class variable here
SomeOtherObject someOtherObject = getSomeObject(myCommonObject,someForm);
modelMap.addAttribute("someOtherObject",someOtherObject);
return new ModelAndView("/secondJSP");
}
@RequestMapping(value="/demo-three", method=RequestMethod.POST)
public ModelAndView postControllerThree(@ModelAttribute SomeForm someForm,
ModelMap modelMap)
{
// Used the class variable here
SomeOtherObject someOtherObject = getSomeObject(myCommonObject,someForm);
modelMap.addAttribute("someOtherObject",someOtherObject);
return new ModelAndView("/thirdJSP");
}
@RequestMapping(value="/demo-four", method=RequestMethod.POST)
public ModelAndView postControllerFour(@ModelAttribute SomeForm someForm,
ModelMap modelMap)
{
// Used the class variable here
SomeOtherObject someOtherObject = getSomeObject(myCommonObject,someForm);
modelMap.addAttribute("someOtherObject",someOtherObject);
return new ModelAndView("/fourthJSP");
}
}
谢谢。
最佳答案
DemoController
是一个单例。所有网络请求都只有一个实例。
这意味着整个 Web 应用中只有一个 myCommonObject
值。最后点击 /demo-one
的人获胜,并且对 /demo-two
到 /demo-four
的所有点击都将使用最后一个实例,无论谁在做这件事。
我假设MyCommonObject
存储状态信息,否则为什么要做你想做的事情。每次任何人点击/demo-one
时都会重置此状态对象。不能那样做。简而言之,不要将状态存储在 Controller 中。
由于您希望每个客户端都有一个 MyCommonObject
实例,因此请将其存储在 HttpSession
中。
关于java - 在不同的 Controller 中使用一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37626744/