如何在Spring中将对象从一个控制器传递到另一个控制器而不使用Session [英] How to pass the object from one controller to another in Spring without using Session

查看:130
本文介绍了如何在Spring中将对象从一个控制器传递到另一个控制器而不使用Session的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a requirement where the user selects some data from a form and we need to show that selected data on the next page.

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

At present we are doing this with a session attribute, but the problem with this is that it overwrites the data if the first page is open in another browser tab, where the data is again selected and submitted. So I just want to get rid of this session attribute while transferring data from one controller to another.

注意:我使用的是基于XML的Spring配置,所以请显示一个使用XML而不是注释的解决方案。

Note: I am using an XML based Spring configuration, so please show a solution using XML, not annotations.

推荐答案

定义 RedirectAttributes 方法参数从第一页处理表单提交处理程序方法:

Define RedirectAttributes method parameter in the the handler method that handles form submission from first page:

@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";
}

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

The flash attributes are saved temporarily before the redirect (typically in the session) and are available to the request after the redirect and removed immediately.

上述重定向将导致客户端(浏览器)向 / secondPageURL发送请求。所以你需要一个处理程序方法来处理这个请求,你可以在那里访问 submitForm DataObject数据 $ c>处理程序方法:

The above redirect will cause the client (browser) to send a request to /secondPageURL. So you need to have a handler method to handle this request, and there you can get access to the DataObject data set in the submitForm handler method:

@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数据是包含来自 submitForm 方法的数据的对象。

Here DataObject data is the object that contains data from the submitForm method.

这篇关于如何在Spring中将对象从一个控制器传递到另一个控制器而不使用Session的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆