简体   繁体   中英

How to create new object on each button click in Java ee?

I'm practising Java ee and I made a two input fields and button in jsp. When clicked on button "add" I want to add those two fields in a list and just show them on my jsp page. For now it's showing me only one result each time I click on button. What am I doing wrong?

This is my jsp:

<body>
    <form action="addtocart" method="GET">
        Title: <input type="text" name="title"> <br>
        Price: <input type="text" name="price"> <br>
        <button type="subtmit">Add</button>
    </form>
    <c:forEach var="bookList" items="${book}"> 
        <ul>
            <li>${bookList.name}</li>
            <li>${bookList.price}</li>
        </ul>          
    </c:forEach>
</body>

And this is my servlet:

  protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {    
        HttpSession session = request.getSession(true);
        String title = request.getParameter("title");
        double price = Double.parseDouble(request.getParameter("price"));
        ArrayList<Book> list = new ArrayList<>();    
        list.add(new Book(title,price));   
        session.setAttribute("book", list);      
        RequestDispatcher rd = request.getRequestDispatcher("home.jsp");
        rd.forward(request, response);
    }

Problem

You are creating a new ArrayList<Book> on every call of doGet and setting the same into the session. Thus, on every call of doGet the list is getting reset.

Solution

Get the existing list from the session and add a book to it. Create a new list only when it is not present in the session.

@WebServlet("/addtocart")
public class BooklistServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession(true);
        String title = request.getParameter("title");
        double price = Double.parseDouble(request.getParameter("price"));
        ArrayList<Book> list = (ArrayList<Book>) session.getAttribute("book");
        if (list == null) {
            list = new ArrayList<Book>();
        }
        list.add(new Book(title, price));
        session.setAttribute("book", list);
        RequestDispatcher view = request.getRequestDispatcher("home.jsp");
        view.forward(request, response);
    }
}

Additionally, I recommend you display the list only when it is not empty as shown below:

<body>
    <form action="addtocart" method="GET">
        Title: <input type="text" name="title"> <br> Price: <input
            type="text" name="price"> <br>
        <button type="submit">Add</button>
    </form>
    <c:forEach var="bookList" items="${book}">
        <c:if test="${not empty book}">
            <ul>
                <li>${bookList.title}</li>
                <li>${bookList.price}</li>
            </ul>
        </c:if>
    </c:forEach>
</body>

As you can see, I've added the check <c:if test="${not empty book}"> as a condition for the visibility of the list.

Every time the statement session.setAttribute("book", list); runs, it replaces the previous list in the session with the new one.

You should first try to fetch the existing list and then add your current book object to it.

ArrayList<Book> list =(ArrayList<Book>)session.getAttribute("book");  // get the current list from the session
list.add(new Book(...));
session.setAttribute("book", list);  // store list in session

This should give you the output you are asking for.. Make sure you handle the NullPointerException that may be thrown when you add the element in the list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM