为什么在GET重定向上清除SessionAttributes?

时间:2013-06-13 11:43:32

标签: java spring spring-mvc

为简单起见,这些代码片段将会缩短。这样做的目的是获取GET参数,在会话上设置它,并在删除url参数的情况下重定向回GET。基本上,URI清理。如果有更好/更简单的方法,我会很高兴听到它。

我有一个如此定义的控制器:

@Controller
@RequestMapping("/path/page.xhtml")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@SessionAttributes({ "myParam1", "myParam2" })
public class MyController {

  @RequestMapping(method = RequestMethod.GET, params = { "urlParam2" })
  public String handleUriParam(@RequestParam(value = "urlParam2", required = false)
                               final Long urlParam2,
                               final RedirectAttributes redirs) {
    // at this point, myParam1 is set on the session.
    // now set the param as a flash attrib with the name of the session variable
    redirs.addFlashAttribute("myParam2", urlParam2);
    return "redirect:/path/page.xhtml";
  }

  @RequestMapping(method = RequestMethod.GET, params = {})
  public String doGetStuff(ModelMap model) {
    // do stuff using myParam1 and myParam2.
    // problem is, myParam2 is on the session, but myParam1 is not!
  }

}

就像代码所说的那样,当重定向发生时,某种方式myParam1未被设置。我可以通过将ModelMap传递给handleUrlParam方法并手动将myParam1添加到Flash属性来解决此问题,但这似乎在我的脑海中打败了目的。

为什么重定向后会移除SessionAttribute myParam1

有没有更好的方法从URI中提取参数并将它们放在会话中?

更新

因此,无论何时使用RedirectAttributes,您都必须确保将要携带的任何SessionAttribute放入FlashAttributes的重定向中,否则它们将丢失。我想这会发生这种情况,因为SessionAttribute被拉出ModelMap(使用时被FlashAttributes取代)。这是Spring中的错误还是故意行为?如果是故意的,有人可以解释原因吗?我认为SessionAttribute s应该保持开启,直到完成对话会话后才会删除。

Similar StackOverflow post here

附录

根据所提供的答案,我仍然难以理解如何在将URI参数放入用户会话时清除它们。我考虑过的一个选项是为我试图存储的半原始对象(java.lang.Integer,java.lang.String)创建一个包装器,因为它们不会放在URI字符串上,但这似乎很难得我。如果有人有更好的方式接受GET参数,将它们存储在用户的会话中,并清除用户地址栏中的那些(这将需要重定向),我很乐意使用它。

1 个答案:

答案 0 :(得分:6)

所以我在寻找代码和互联网,找出它无法正常工作的原因。

Spring有两个完全独立的模型映射 - 一个用于标准视图渲染,另一个用于发出重定向。这可以在ModelAndViewContainer中观察到。

现在会话属性持久性已完成based on the result from mavContainer#getModel()。对于重定向方案,这将返回重定向模型。因此,您在标准Model / ModelMap上设置的内容将丢失。

在谈论标准模型属性时,这是有意义的。 Model主要是将对象传递给视图。使用重定向时,您处理的是完全不同的情况。您希望通过HTTP重定向传输对象 - 因此分离的字符串和基于闪存的模型。

但我的感觉是他们在designing this feature时忘记了会话属性。有一些不错的discussion in Spring's Jira,但是它们都没有解决这个特定的问题。

所以是的......这可能是Spring的Jira主题。 可能被归类为错误,因为这会阻止任何人设置会话使用重定向时的模型属性。强制Spring通过RedirectAttributes#addFlashAttribute存储您的会话属性是IMO的一种黑客攻击和错误

相关问题