Home » Java » Java Servlet list.remove not working

Java Servlet list.remove not working

Posted by: admin August 10, 2018 Leave a comment

Questions:

I have a list of strings the list.add works just fine but the list.remove is not working. this is my code:

public class CartServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

public List<String> cart = new ArrayList<String>();
public CartServlet() {
    super();
    // TODO Auto-generated constructor stub
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //cart.forEach(System.out::println);
    request.setAttribute("cart",cart);
    request.getRequestDispatcher("WEB-INF/Cart.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String productAdd = request.getParameter("add");
    String productDelete = request.getParameter("delete");
    if(productAdd != null) {
        cart.add(productAdd);
        //System.out.println(cart.indexOf(productAdd));

    }
    else {
        cart.remove(productDelete);//this is not working
    }
    doGet(request, response);
}

}

I add like this:
add item

Then my cart is:
cart
I remove the same way, with a button. But for some reason i get the productDelete correctly but cart.remove(productDelet) doesnt work, and the string is there, I feel like the Strings dont match.

Answers: