在Java Servlet中添加和打印会话中的值

Add and print values from a session in Java Servlets?

本文关键字:会话 打印 添加 Java Servlet      更新时间:2023-09-26

好的,我有这个购物车代码,每当按下任何"添加到购物车"按钮时,它都会输出不同的游戏名称、数量和价格。问题是,假设我买了2个同一款游戏和2个另一款游戏,它会显示每个游戏的总金额,而不是所有游戏的总数量。

所以,我遇到的问题是计算所有游戏的总量并将其打印在一起,然后我想将值与游戏名称一起写入文件。

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Cart extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String s, goods[] = {"Fifa 15", "Battlefield 4", "GTA 5", "The Last of US"};
int price []={59,49,69,39};
int cost;
PrintWriter out = res.getWriter();
res.setContentType("text/html");
HttpSession session = req.getSession(true);
if ( session == null ) return;
for (int i = 0; i < goods.length; i++){
    if ( session.getAttribute(goods[i]) == null )
    session.setAttribute(goods[i], new Integer(0));}
if ((s = req.getParameter("fifa")) != null) {
        int n = ((Integer) session.getAttribute(goods[0])).intValue();
        session.setAttribute(goods[0], new Integer(n + 1));
    } else if ((s = req.getParameter("battle")) != null) {
        int n = ((Integer) session.getAttribute(goods[1])).intValue();
        session.setAttribute(goods[1], new Integer(n + 1));
    } else if ((s = req.getParameter("gta")) != null) {
        int n = ((Integer) session.getAttribute(goods[2])).intValue();
        session.setAttribute(goods[2], new Integer(n + 1));
    } else if ((s = req.getParameter("lou")) != null) {
        int n = ((Integer) session.getAttribute(goods[3])).intValue();
        session.setAttribute(goods[3], new Integer(n + 1));
    }
out.println("<html><body><h2>Shopping Cart:</h2><ul>");
out.println("Items that have been Successfully added to Your Shopping Cart: ");
out.println();
for (int i = 0; i < goods.length; i++) {
    int n = ((Integer)session.getAttribute(goods[i])).intValue();
    if ( n > 0 )
    {out.println("<li><b>" + goods[i] + "</b> : " + n +" pcs for the price of $"+price[i] +"</li>");
        cost=n*price[i];
        out.println("$"+cost);}
    }
out.println("</ul></body></html>");

如果我不喜欢,你想要总数吗?

int n;
int total = 0;
for (int i = 0; i < goods.length; i++) {
    n = ((Integer)session.getAttribute(goods[i])).intValue();
    if ( n > 0 ) {
        out.println("<li><b>" + goods[i] + "</b> : " + n +" pcs for the price of $"+price[i] +"</li>");
        cost=n*price[i];
        total=total+cost;
        out.println("$"+cost);
    }
    out.println("Total is : $"+total);
}