0

I just want with each button click to add price value. This is my jsp:

<body>
<h1>Welcome ${user.name}</h1>
<c:forEach var="artical" items="${articals}">
    <ul>
        <li>${artical.name} </li>
        <li>${artical.price}</li>
        <li>${priceSum}</li> // i want to show value here just to test it.
    </ul>
    <form action="addtocart" method="POST">
        <input type="hidden" name="names" value="${artical.name}"/>
        <input type="hidden" name="price" value="${artical.price}"/>
        <button type="submit" name="button">Add to cart</button>
    </form>              
</c:forEach>

And this is my servlet:

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
HttpSession session = request.getSession(true);
String name = request.getParameter("names");
double price = Double.parseDouble(request.getParameter("price"));
double priceSum = 0;
priceSum += price;
session.setAttribute("names", name);
session.setAttribute("price", price);
session.setAttribute("priceSum", priceSum);
RequestDispatcher rd = request.getRequestDispatcher("home.jsp");
rd.forward(request, response);
 }

Now when i put priceSum outside doPost method as an attribute, it works, but i heard it shouldn't be solved like that. So how can i solve this properly and why is bad to put variable outside methods in servlets? Thanks!

1 Answers1

0

I solve problem like this:

     protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession(true);
    String name = request.getParameter("names");
    double price = Double.parseDouble(request.getParameter("price"));
    Double priceSum = (Double) session.getAttribute("priceSum");
    if (priceSum == null) {
        priceSum = 0.0;
    }
    priceSum+=price;
    session.setAttribute("names", name);
    session.setAttribute("price", price);
    session.setAttribute("priceSum", priceSum);
    RequestDispatcher rd = request.getRequestDispatcher("home.jsp");
    rd.forward(request, response);

}

Is this proper way to do it?