[英]Store List of objects in Session/HttpSession object in Spring
Hi all i want to store list of objects in session object. 大家好,我想在会话对象中存储对象列表。 To store 1 obj i've got this code:
要存储1个obj,我需要以下代码:
@Controller
@SessionAttributes("temp")
@RequestMapping(value = "/test")
public class TestController {
@ModelAttribute("temp")
public Temp setObj() {
return new Temp();
}
@RequestMapping(method = RequestMethod.GET)
public String test(Model model) {
model.addAttribute("temp", new Temp());
return "testInput";
}
@RequestMapping()
public String add(@ModelAttribute("temp") Temp temp, Model model) {
model.addAttribute("temp", temp);
return "test";
}
@RequestMapping(value = "/get") // or "/getList" to ensure it works
public String kek(@ModelAttribute("temp") Temp temp, Model model) {
model.addAttribute("temp", temp);
return "test";
}
}
Where 哪里
class Temp implements Serializible {
//constructor fields, methods
}
PS storing 1 object works fine. PS存储1个对象可以正常工作。
But how can i store List<Temp>
in Session object and add extra Temp
obj with controller? 但是如何将
List<Temp>
存储在Session对象中,并使用控制器添加额外的Temp
obj? Or maybe i should use smth like: 或者也许我应该像这样使用smth:
class TempList {
private List<Temp> list
//constructor, get/set addToList methods
}
If yes, how can i init this class and use tempListObj.addToList(Temp temp)
method? 如果是,我如何初始化此类并使用
tempListObj.addToList(Temp temp)
方法?
For your information if your store object into session with @SessionAttributes annotation so this object will be available only in scope of this controller. 供您参考,如果您的存储对象进入带有@SessionAttributes批注的会话中,则此对象仅在此控制器的范围内可用。 If you want to store List to session, you can just define @SessionAttributes({"temp"}) on class level, and set this into session in any controller method like this:
如果要将List存储到会话中,则只需在类级别定义@SessionAttributes({“ temp”}),然后在任何控制器方法中将其设置为session即可,如下所示:
model.addAttribute("temp", new ArrayList<Temp>());
Then you can get access to this by this way: 然后,您可以通过以下方式对此进行访问:
public String someMethod(@ModelAttribute("temp") List<Temp> temp) {...}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.