从视图返回时,Session属性返回null

时间:2013-03-31 17:17:44

标签: java spring jsp spring-mvc

我目前正在尝试将搜索条件属性保存到两个页面之间的会话:搜索页面和编辑页面。目标是保存三个变量:sYear,submission,collectionPeriod。我将这些添加到下面的搜索屏幕控制器中的会话:

request.getSession().setAttribute("sYearSave", sYear); request.getSession().setAttribute("submissionSave", submission); request.getSession().setAttribute("collectionPeriodSave", collectionPeriod);

在编辑屏幕控制器中,我将布尔isFromEditScreen设置为true.这是我知道我来自编辑屏幕。我打印出变量,我确实在编辑控制器屏幕中正确获取了值。

request.getSession().setAttribute("isFromEditScreen", new Boolean(true));
    sYearSave = (String)request.getSession().getAttribute("sYearSave");
    collectionPeriodSave = (String)request.getSession().getAttribute("collectionPeriodSave");
    submissionSave = (String)request.getSession().getAttribute("submissionSave");

但问题是当我使用后退按钮返回搜索屏幕时,搜索条件sYearSave, collectionPeriodSave, and submissionSave值返回NULL.出于某种原因,isFromEditScreen布尔值工作得很好并返回true.它实际进入语句但搜索条件返回null.搜索控制器代码如下:

if (isFromEditScreen != null && isFromEditScreen == true) {
        System.out.println("Inside isFromEditScreen ==== true");
        sYear = (String)request.getSession().getAttribute("sYearSave");
        collectionPeriod = (String)request.getSession().getAttribute("collectionPeriodSave");
        submission = (String)request.getSession().getAttribute("submissionSave");


        sYearSave = (String)request.getSession().getAttribute("sYearSave");
        collectionPeriodSave = (String)request.getSession().getAttribute("collectionPeriodSave");
        submissionSave = (String)request.getSession().getAttribute("submissionSave");

        System.out.println("sYearSave ==== " + sYearSave);
        System.out.println("submissionSave ==== " + submissionSave);
        System.out.println("collectionPeriodSave ==== " + collectionPeriodSave);
        System.out.println("isFromEditScreen set in else ==== " + isFromEditScreen);
        }

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

如果您正在使用Spring MVC(如问题标签所示),为什么不尝试使用SessionAttributes注释并使用Spring的ModelAndView API?还要确保应用程序中的属性名称是唯一的。

@RequestMapping("view-name")
@SessionAttributes( { "isFromEditScreen" })
public class YourController {

...

    @RequestMapping
    public ModelAndView display() {

        ModelAndView modelAndView = new ModelAndView("view-name");
        modelAndView.addObject("isFromEditScreen", new Boolean(true));
        return modelAndView;
    }

...
}

答案 1 :(得分:0)

我的会话属性被覆盖了。忽略了错误。