本文介绍了当SpringMVC中的@SessionAttributes什么时候被删除? (带代码示例)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

@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.

但是如果第二个方法的签名被修改为this ...

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:

但我不

任何人都可以解释这个行为,或者是一个错误?

Can anyone explain this behaviour or is it a bug?

推荐答案

您表示通过调用

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.

您尝试过以下操作:

@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什么时候被删除? (带代码示例)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 04:12