如何在每个请求中逐个存储多个对象?

时间:2016-03-29 12:00:22

标签: java list session httpsession

我正在为应用程序工作,我必须为每个请求发送一个对象。我必须将整个数据存储在会话变量中。我该怎么做?我将数据发送到控制器并创建对象,然后尝试存储在会话中,但它不起作用,这是我的代码

MemberDependentBO memberdepinfo = new MemberDependentBO();

        memberdepinfo.setFirstName(getMemberFirstName().getValue().toString());
        memberdepinfo.setLastName(getMemberLastName().getValue().toString());
        memberdepinfo.setMiddleName(getMemberMiddleName().getValue().toString());
        memberdepinfo.setPassport(getMemberPassportNumber().getValue().toString());

    List<MemberDependentBO> listOfMemberAndDep = new ArrayList<MemberDependentBO>();

        listOfMemberAndDep.add(memberdepinfo);

        httpSession.setAttribute("insuredInfo", listOfMemberAndDep);

        System.out.println("List Size :"+listOfMemberAndDep.size());
  

每次单击按钮时,对象都来自   控制器。但每次我得到列表的大小是1.任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

首先尝试从当前会话中拉出listOfMemberAndDep。如果它不存在,请创建它,添加memberdepinfo并保存在会话中。如果确实存在,只需添加memberdepinfo并在会话中重新保存。像这样......

List<MemberDependentBO> listOfMemberAndDep = (List<MemberDependentBO>)httpSession.getAttribute("insuredInfo");

if(listOfMemberAndDep == null){
    listOfMemberAndDep = new ArrayList<MemberDependentBO>();
}

MemberDependentBO memberdepinfo = new MemberDependentBO();
memberdepinfo.setFirstName(getMemberFirstName().getValue().toString());
memberdepinfo.setLastName(getMemberLastName().getValue().toString());
memberdepinfo.setMiddleName(getMemberMiddleName().getValue().toString());
memberdepinfo.setPassport(getMemberPassportNumber().getValue().toString();

listOfMemberAndDep.add(memberdepinfo);
httpSession.setAttribute("insuredInfo", listOfMemberAndDep);
System.out.println("List Size :"+listOfMemberAndDep.size());