我正在尝试将对象添加到会话中存储的ArrayList中。
似乎没有添加该对象。
请检查我的以下代码,并为此建议一个正确的答案。
调试我的调试器直到此代码books.add(book);
,然后它跳过剩余的代码。我知道问题在这里books.add(book);
。书籍详细信息未添加到我的arraylist books
。
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>
答案 0 :(得分: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可能会使测试变得比必要更困难。