?? shoppingservlet.java
字號:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import changpian.CP;
public class ShoppingServlet extends HttpServlet {
public void doPost (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
HttpSession session = req.getSession(true);
req.setCharacterEncoding("GBK");
Vector vector=(Vector)session.getAttribute("total");
String action = req.getParameter("action");
if (!action.equals("checkout")) {
if (action.equals("delete")) {
String del = req.getParameter("delindex");
int index = Integer.parseInt(del);;
vector.removeElementAt(index); // 從vector中將相應的數據刪除
} else if (action.equals("add")) {
//以前是否購買了同樣的cd
boolean again=false; //again變量表示是否以前購買過相同的cd
CP newCp = getCD(req);
if (vector==null) {
vector = new Vector();
vector.addElement(newCp);
} else { // 不是第一次購買
for (int i=0; i< vector.size(); i++) {
CP cd = (CP) vector.elementAt(i);
//判斷購買的cd是否已經買過
if (cd.getName().equals(newCp.getName())) {
cd.setQuantity(cd.getQuantity()+newCp.getQuantity());
vector.setElementAt(cd,i);
again = true;
}
}
//如果購買的cd在前面沒有買過
if (!again)
vector.addElement(newCp);
}
}
session.setAttribute("total", vector);
String url="/shop.jsp";
getServletConfig().getServletContext().getRequestDispatcher(url).forward(req, res);
} else if (action.equals("checkout")) {
float total =0;
for (int i=0; i< vector.size();i++) {
CP one = (CP) vector.elementAt(i);
float price= one.getPrice();
int qty = one.getQuantity();
total += (price * qty);
}
total += 0.005;
String amount = "" + total;
int n = amount.indexOf('.');
amount = amount.substring(0,n+3);
req.setAttribute("amount",amount);
String url="/checkout.jsp";
getServletConfig().getServletContext().getRequestDispatcher(url).forward(req, res);
}
}
private CP getCD(HttpServletRequest req) {
String cdname = req.getParameter("CD");
String qty = req.getParameter("qty");
StringTokenizer st = new StringTokenizer(cdname,"|");
String name = st.nextToken();
String artist = st.nextToken();
String country = st.nextToken();
String price = st.nextToken();
price = price.replace('$',' ').trim();
CP cp = new CP();
cp.setName(name);
cp.setArtist(artist);
cp.setCountry(country);
cp.setPrice(Float.parseFloat(price));
cp.setQuantity(Integer.parseInt(qty));
return cp;
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -