-2

I am trying to add an object into an ArrayList stored in the session.

The object doesn't seem to be added.

Please check my below code and suggest me a correct answer for this.

While debugging my debugger goes till this code books.add(book); and then it skips the remaining code. I know problem is here books.add(book); . Book detail is not adding into my 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>
Dan
  • 2,086
  • 11
  • 71
  • 137
  • 2
    It looks like the error is in the next line: `books = new ArrayList();`. – Luiggi Mendoza Nov 10 '12 at 16:45
  • Also, these 2 lines have no sense: `session.put(BillTransactionBooksConstants.BOK, books ); books = (List) session.get( BillTransactionBooksConstants.BOK );`. You create a new `List`, save it in session and retrieve it. How would you expected to still have the first list to begin with? – Luiggi Mendoza Nov 10 '12 at 16:46
  • @LuiggiMendoza With those two lines i am adding list into my session in order to creat Customer Bill.. more details in this link (http://stackoverflow.com/questions/13320293/how-to-add-object-in-a-arraylist-one-by-one-in-order-to-make-a-complete-list) – Dan Nov 10 '12 at 16:49
  • While the question isn't struts 2-related, please take some time to understand better ways to use the framework. – Dave Newton Nov 10 '12 at 16:50
  • @AshutoshSingh You don't need to add the list back to the session because both objects (the session attribute containing the list and the list) are pointing to the same memory location, if you update one of them the other is updated at the same time. – Luiggi Mendoza Nov 10 '12 at 16:51
  • @Dave Newton `public class AddBookToSession extends ActionSupport` is struts2 uses for performing some tasks. And this is just a small program from my application. I am developing my application in struts2 – Dan Nov 10 '12 at 16:52
  • Also, the loop `for(int i=1;i<=1;i++)` will only ever run once. – DNA Nov 10 '12 at 16:54
  • @LuiggiMendoza Now i update my code by removing `books = (List) session.get( BillTransactionBooksConstants.BOK );` But still i have problem in this line `books.add(book);` . I do't know why object `book `is not adding into my arraylist obj `books` – Dan Nov 10 '12 at 16:55
  • please help me..i am trying since 3hrs to solve this issue – Dan Nov 10 '12 at 17:00
  • I'm not a struts2 developer, so let me ask you, this `AddBookToSession` class gets instantiated on every request or it's handled by the framework in a similar way that the web server handles a servlet? – Luiggi Mendoza Nov 10 '12 at 17:04
  • @LuiggiMendoza when a user clicks on a row then the rowId is passed to the class `AddBookToSession` as a parameter . I want to add the clicked row into a list `books` in order to make a customer Bill. This `AddBookToSession` class is called when a user click on the row in a jsp page. – Dan Nov 10 '12 at 17:11
  • This could be silly, but have you made sure that there's a list in the session and you're using **the same name** to save and retrieve it? – Luiggi Mendoza Nov 10 '12 at 17:20
  • Why do you create so many lists? You should be adding the book to the list retrieved from the session, and that's all. You should use SessionAware, and should use Struts 2's property access instead of retrieving from the request. Right now you're basically writing a servlet inside a framework that gives you a lot more. – Dave Newton Nov 10 '12 at 17:25
  • Not sure how that's relevant, but ok. What do you think I said? – Dave Newton Nov 10 '12 at 17:35
  • @AshutoshSingh Please note that if you don't use an `@` tag people you're replying to won't be notified. Also note that if you've actually retrieved a book, the only code that matters is in the action--the rest is not relevant. – Dave Newton Nov 10 '12 at 17:56
  • @LuiggiMendoza i have a interface named `BillTransactionBooksConstants` and i am putting my list books into this way `session.put(BillTransactionBooksConstants.BOK, books );` and getting those list in this way `books = (List) session.get(BillTransactionBooksConstants.BOK);` – Dan Nov 10 '12 at 18:01
  • @LuiggiMendoza and interface is like this `package v.esoft.actions.booktransaction; public class BillTransactionBooksConstants { public static final String BOK = "BOK"; }` – Dan Nov 10 '12 at 18:03
  • @LuiggiMendoza Now i added full code. Please check and suggest me a solution for my problem – Dan Nov 10 '12 at 18:03
  • @AshutoshSingh And if your debugger is randomly skipping code you have a larger problem than something merely framework-/understanding-related. – Dave Newton Nov 10 '12 at 18:16
  • @DaveNewton i also tried like in this way (click on the link) http://stackoverflow.com/questions/13320293/how-to-add-object-in-a-arraylist-one-by-one-in-order-to-make-a-complete-list – Dan Nov 10 '12 at 18:24
  • @AshutoshSingh Oh, so this is a duplicate question? I see. In any case, the code in my answer, and as suggested by others, is the correct code. – Dave Newton Nov 10 '12 at 18:32
  • @DaveNewton sorry , but what do you mean by this _"and as suggested by others, is the correct code"_ – Dan Nov 10 '12 at 18:37
  • @AshutoshSingh Everybody said the same thing, you know. – Dave Newton Nov 10 '12 at 18:41
  • @DaveNewton i have a small problem. Please check this http://stackoverflow.com/questions/13807092/error-java-util-concurrentmodificationexception/13807321#13807321 . – Dan Dec 10 '12 at 19:25

1 Answers1

1

You add a new, empty list to session:

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);

That said, your action code should look something closer to this (untested):

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

Note that instantiating a book DAO like this may make testing a bit more difficult than necessary.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
  • I tested this code It is fine. But i need getter setter in order to set the books list into my jsp page, then only i can show the added iterate the list into my jsp. How can i make getter setter of books in this class? – Dan Nov 10 '12 at 18:48
  • list size is coming correct -> .... `if (book != null) { List books = sessionBooks(); HttpServletRequest request = ServletActionContext.getRequest(); books.add(book); System.out.println("books size"+books.size()); } return SUCCESS;}` – Dan Nov 10 '12 at 18:49
  • @AshutoshSingh How can you create a getter? By creating a getter. You don't need a setter. Just make `books` an action property instead of a method property. – Dave Newton Nov 10 '12 at 18:58
  • Or just tell me how can i show my list from session in jsp using struts2 tag. eg. i want to show the list which i have added in session with this name -BillTransactionBooksConstants.BOK- – Dan Nov 10 '12 at 19:00
  • You told me "_Just make books an action property instead of a method property_" . What is the meaning of this? Please explain this in little detail – Dan Nov 10 '12 at 19:13
  • @AshutoshSingh ... Right now 'books' is a variable local to the method. If you make it an action variable and expose it via a getter, it's an action property. Or you can access it directly from the session using normal Struts 2 session variable access. Have you read any of the docs? I don't know what all that HTML you tried to put into a comment is for--if you're trying to illustrate something, show only the basics, not the surrounding styles, tables, etc. – Dave Newton Nov 10 '12 at 19:15
  • yes you are right. i should not show unnacessary code (like html) while asking question. Next time if i ask anything , i will put only code which are exactly related to my question – Dan Nov 10 '12 at 19:27
  • I have a new doubt. -> i do't want to add same data more then once into my session arraylist. what is logic behind this?how can i do this? Currently above code is inserting list based on the `bookid` . – Dan Nov 11 '12 at 06:54
  • @AshutoshSingh Check the list to see if it's already in the list? – Dave Newton Nov 11 '12 at 07:57
  • I tried but it was not comming. I know nicely how to avoid dublicate insertion of data into database using struts2,hibernate But i have never did with Arraylist. Then finally i posted my doubt in this link after giving a try for that. http://stackoverflow.com/questions/13330209/how-to-compare-avoid-insertion-of-dublicate-data-into-arraylist – Dan Nov 11 '12 at 11:06