SpringMVC 中的@SessionAttributes 什么时候被删除?(带代码示例) [英] When do @SessionAttributes in SpringMVC get removed? (With code sample)
问题描述
@SessionAttributes 在什么确切情况下被清除?在尝试在页面中使用两个模型时,我发现了一些令人困惑的行为.
Under what exact circumstances do @SessionAttributes get cleared? I've discovered some confusing behaviour when trying to use two models in a page.
当我使用此控制器执行 GET 和 POST 时...
When I do a GET followed by a POST using this controller...
@Controller
@RequestMapping("/myPage*")
@SessionAttributes(value = {"object1", "object2"})
public class MyController {
@RequestMapping(method = RequestMethod.GET)
public String get(Model model) {
model.addAttribute("object1", new Object1());
model.addAttribute("object2", new Object2());
return "myPage";
}
@RequestMapping(method = RequestMethod.POST)
public String post(@ModelAttribute(value = "object1") Object1 object1) {
//do something with object1
return "myPage";
}
}
...object2 从模型中清除.它不再作为@SessionAttribute 存在并且无法在我的视图页面上访问.
...object2 gets cleared from the Model. It no longer exists as a @SessionAttribute and cannot be accessed on my view page.
但是如果把第二种方法的签名修改成这样...
However if the signature of the second method is modified to this...
public String post(@ModelAttribute(value = "object1") Object1 object1,
@ModelAttribute(value = "object2") Object2 object2) {
...然后 object2 不会从模型中清除并且在我的视图页面上可用.
...then object2 does not get cleared from the model and is available on my view page.
@SessionAttributes 的 javadoc 说:
The javadoc for @SessionAttributes says:
... 属性将被删除一次处理程序指示完成它的会话会话.
... attributes will be removed once the handler indicates completion of its conversational session.
但是我没有看到我是如何在第一个示例中指示会话会话完成的,而在第二个示例中却没有.
But I don't see how I have indicated completion of the conversational session in the first example but not in the second example.
任何人都可以解释这种行为还是它是一个错误?
Can anyone explain this behaviour or is it a bug?
推荐答案
您通过调用来表示对话的完成
You indicate completion of the conversation by calling
SessionStatus.setComplete
public void post(...., SessionStatus status) {
status.setComplete();
}
也就是说,我不明白为什么您应该丢失一个模型属性而不是另一个.
That said, I don't see why you should be loosing one model attribute and not the other.
你有没有试过做这样的事情:
Have you tried doing something like:
@ModelAttribute("object1")
public Object object1() { return new Object(); }
@ModelAttribute("object2")
public Object object2() { return new Object(); }
看看这与手动将属性放入模型相比如何.
And see how that compares to putting the attributes in the model by hand.
这篇关于SpringMVC 中的@SessionAttributes 什么时候被删除?(带代码示例)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!