-2

我正在尝试将一个对象添加到存储在会话中的 ArrayList 中。

该对象似乎没有被添加。

请检查我的以下代码并为此建议我一个正确的答案。

在调试时,我的调试器会一直运行到这段代码books.add(book);,然后它会跳过剩余的代码。我知道问题就在这里books.add(book);。书籍详细信息未添加到我的 arraylistbooks中。

AddBookToSession.java

    public class AddBookToSession extends ActionSupport {
         Bookdetails book=new Bookdetails();
            List<Bookdetails> books = new ArrayList<Bookdetails>();

            BookdetailsDAO dao = new BookdetailsDAO(); 
      Map session = ActionContext.getContext().getSession();

        public String execute()
        { 
            HttpServletRequest request = ServletActionContext.getRequest();  
            String bookid = request.getParameter("bid");    
            books = (List) session.get( BillTransactionBooksConstants.BOK ); 
          for(int i=1;i<=1;i++)
        {
          book = dao.listBookDetailsById(Integer.parseInt(bookid));    
          books.add(book); //problem is here obj book is not adding into books list

          books = new ArrayList<Bookdetails>();

          System.out.println("---------------Bookid-"+book); 
        }
        ....................
                ...............

struts.xml

        <package name="testwithrowselect" extends="struts-default" >  
                    <action name="InsertbooksToSession" class="v.esoft.actions.booktransaction.AddBookToSession">
                        <result name="success">/jspHomepage/bookstransaction/shortBill.jsp</result>  
                    </action>
         </package>
4

1 回答 1

1

您向会话添加一个新的空列表:

for (int i = 1; i <= 1; i++) {
    book = dao.listBookDetailsById(Integer.parseInt(bookid));    
    books.add(book);
    books = new ArrayList<Bookdetails>(); // <-- Now it's a new, empty list?!
}
session.put(BillTransactionBooksConstants.BOK, books);

也就是说,您的操作代码应该看起来更接近这个(未经测试):

public class AddBookToSession extends ActionSupport implements SessionAware {

    private Integer bid;
    private Map<String, Object> session;

    private BookdetailsDAO dao = new BookdetailsDAO(); 

    public String execute() { 
        BookDetails book = dao.listBookDetailsById(Integer.parseInt(bookid));
        if (book != null) {
            List<Bookdetails> books = sessionBooks();
            books.add(book);
        }

        return SUCCESS;
    } 

    private List<Bookdetails> sessionBooks() {
        List<Bookdetails> books = (List) session.get(BillTransactionBooksConstants.BOK);
        if (books == null) {
            books = new ArrayList<BookDetails>();
            session.put(BillTransactionBooksConstants.BOK, books);
        }
        return books;
    }

    public void setSession(Map<String, Object> session) {
        this.session = session;
    }

    public Integer getBid() {
        return this.bid;
    }

    public void setBid(Integer bid) {
        this.bid = bid;
    }
}

请注意,像这样实例化书籍 DAO 可能会使测试变得比必要的更困难。

于 2012-11-10T18:00:46.690 回答