如何在Spring中将对象从一个控制器传递到另一个控制器而不使用Session

我有一个要求,用户从表单中选择一些数据,我们需要在下一页显示所选数据。

目前我们使用会话属性执行此操作,但问题是如果第一页在另一个浏览器选项卡中打开,它将覆盖数据,其中再次选择和提交数据。 所以我只想在将数据从一个控制器传输到另一个控制器时摆脱这个会话属性。

注意:我使用的是基于XML的Spring配置,因此请使用XML而不是注释来显示解决方案。

handler从第一页处理form submissionhandler方法中定义RedirectAttributes方法参数:

 @RequestMapping("/sendDataToNextPage", method = RequestMethod.POST) public String submitForm( @ModelAttribute("formBackingObj") @Valid FormBackingObj formBackingObj, BindingResult result, RedirectAttributes redirectAttributes) { ... DataObject data = new DataObject(); redirectAttributes.addFlashAttribute("dataForNextPage", data); ... return "redirect:/secondPageURL"; } 

闪存属性在重定向之前临时保存(通常在会话中),并且在重定向后可用于请求并立即删除。

上述重定向将导致客户端(浏览器)向/secondPageURL发送请求。 因此,您需要一个处理程序方法来处理此请求,并且您可以在submitForm处理程序方法中访问DataObject data集:

 @RequestMapping(value = "/secondPageURL", method = RequestMethod.GET) public String gotoCountrySavePage( @ModelAttribute("dataForNextPage") DataObject data, ModelMap model) { ... //data is the DataObject that was set to redirectAttributes in submitForm method return "pageToBeShown"; } 

这里DataObject data是包含来自submitForm方法的DataObject data的对象。

我使用了此要求并使用了RedirectAttributes,然后您可以将此重定向属性添加到模型中。 这是一个例子:

 @RequestMapping(value = "/mypath/{myProperty}", method = RequestMethod.POST) public String submitMyForm(@PathVariable Long myProperty, RedirectAttributes redirectAttributes) { redirectAttributes.addFlashAttribute("message", "My property is: " + myProperty); return "redirect:/anotherPage"; } @RequestMapping(method = RequestMethod.GET) public String defaultPage(Model model, @RequestParam(required = false) String message) { if(StringUtils.isNotBlank(message)) { model.addAttribute("message", message); } return "myPage"; } 

希望能帮助到你。

您可以使用RedirectAttributes; 控制器可用于为重定向方案选择属性的Model接口的特化。

 public interface RedirectAttributes extends org.springframework.ui.Model 

此外,此界面还提供了一种存储“Flash属性”的方法。 Flash属性在FlashMap中。

FlashMap :FlashMap为一个请求提供了一种存储打算在另一个请求中使用的属性的方法。 从一个URL重定向到另一个URL时,最常需要这样做。 快速示例是

 @RequestMapping(value = "/accounts", method = RequestMethod.POST) public String handle(RedirectAttributes redirectAttrs) { // Save account ... redirectAttrs.addFlashAttribute("message", "Hello World"); return "redirect:/testUrl/{id}"; } 

参考和详细信息在这里