你說的想法是使用會話範圍的bean的一種方法。您可以定義會話範圍POJO:
@Component
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class YourSessionBean{
...
}
然後你就可以在你的控制器類注入它:
@Controller
public class YourController {
@Autowired
private YourSessionBean yourSessionBean;
...
}
您還可以使用@SessionAttributes你的POJO存儲到會話:
public class YourObject {
...
}
,您可以在您的控制器中使用@SessionAttributes
註釋將YourObject
的實例放入會話中:
@Controller
@SessionAttributes("yourObj")
public class YourController {
...
@RequestMapping(value="/url")
public ModelAndView process(...) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("yourObj", new YourObject()); // this will put YourObj into session
return modelAndView;
}
}
但是,在使用@SessionAttributes
,你應該考慮下面的語句塊(從@SessionAttributes Doc複製):
注意:使用此批註 指示對應於一個特定的處理程序的模型會話屬性的屬性,讓在會話會話中透明地存儲 。一旦 處理程序指示完成其會話會話,那些屬性將被刪除。因此, 使用此功能的這種對話屬性 應該在 特定處理程序的對話過程中臨時存儲在會話中。
對於永久會話屬性,例如,用戶認證對象 改爲使用傳統的session.setAttribute方法。
您還可以使用HttpSession
作爲方法的參數爲您@RequestMapping
處理方法,然後再加入您的POJO類的會話:
@Controller
public class YourController {
...
@RequestMapping(value="/url")
public ModelAndView process(HttpSession session,...) {
ModelAndView modelAndView = new ModelAndView();
session.setAttribute("yourObj", yourObj);
...
return modelAndView;
}
}
謝謝你的答案。 – user1834664
@ user1834664不客氣。 –