在Java Servlet中添加和打印会话中的值
Add and print values from a session in Java Servlets?
好的,我有这个购物车代码,每当按下任何"添加到购物车"按钮时,它都会输出不同的游戏名称、数量和价格。问题是,假设我买了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);
}
相关文章:
- 使用javascript将动态表从一个html页面打印到另一个html页
- JavaScript打印功能使日历停止工作
- esri javascript异步打印
- 文本框不是从Javascript/Asp.net中的对话框中打印出来的
- jQuery/JavaScript在线公文包表单-打印样式表
- 如何打印嵌套对象的所有值
- Flash Uploadify在调用我的MVC控制器时没有保留会话/授权
- 在终端中运行 JavaScript 时(使用 rhino),如何使用 print() 函数在一行中打印
- 打印预览没有应用程序页眉和页脚的html表格
- 正在打印图表上的文本
- 验证会话中是否存在对象's数组
- Rhino打印功能
- 在通过child.print()打印之前,我如何等待图像加载到我的新窗口中
- 通过javascript从会话中提取用户名
- 将会话变量从一个页面传递到另一个页面
- 如果会话中的属性不为 null 或默认值,则运行/打印 JavaScript Razor ASP.NET MVC
- 未打印会话变量
- PHP:为什么当我打印会话的内容时忽略了前导零
- 在Java Servlet中添加和打印会话中的值
- 在javascript中打印哈希表会话变量