import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import shopping.CD;
public class ShoppingServlet extends HttpServlet {
public void init(ServletConfig conf) throws ServletException {
super.init(conf);
}
public void doPost (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
HttpSession session = req.getSession(false);
if (session == null) {
res.sendRedirect("http://localhost:8080/error.html");
}
Vector buylist=
(Vector)session.getValue("shopping.shoppingcart");
String action = req.getParameter("action");
if (!action.equals("CHECKOUT")) {
if (action.equals("DELETE")) {
String del = req.getParameter("delindex");
int d = (new Integer(del)).intValue();
buylist.removeElementAt(d);
} else if (action.equals("ADD")) {
//any previous buys of same cd?
boolean match=false;
CD aCD = getCD(req);
if (buylist==null) {
//add first cd to the cart
buylist = new Vector(); //first order
buylist.addElement(aCD);
} else { // not first buy
for (int i=0; i< buylist.size(); i++) {
CD cd = (CD) buylist.elementAt(i);
if (cd.getAlbum().equals(aCD.getAlbum())) {
cd.setQuantity(cd.getQuantity()+aCD.getQuantity());
buylist.setElementAt(cd,i);
match = true;
} //end of if name matches
} // end of for
if (!match)
buylist.addElement(aCD);
}
}
session.putValue("shopping.shoppingcart", buylist);
String url="/jsp/shopping/EShop.jsp";
ServletContext sc = getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher(url);
rd.forward(req, res);
} else if (action.equals("CHECKOUT")) {
float total =0;
for (int i=0; i< buylist.size();i++) {
CD anOrder = (CD) buylist.elementAt(i);
float price= anOrder.getPrice();
int qty = anOrder.getQuantity();
total += (price * qty);
}
total += 0.005;
String amount = new Float(total).toString();
int n = amount.indexOf('.');
amount = amount.substring(0,n+3);
req.setAttribute("amount",amount);
String url="/jsp/shopping/Checkout.jsp";
ServletContext sc = getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher(url);
rd.forward(req,res);
}
}
private CD getCD(HttpServletRequest req) {
//imagine if all this was in a scriptlet...ugly, eh?
String myCd = req.getParameter("CD");
String qty = req.getParameter("qty");
StringTokenizer t = new StringTokenizer(myCd,"|");
String album= t.nextToken();
String artist = t.nextToken();
String country = t.nextToken();
String price = t.nextToken();
price = price.replace('$',' ').trim();
CD cd = new CD();
cd.setAlbum(album);
cd.setArtist(artist);
cd.setCountry(country);
cd.setPrice((new Float(price)).floatValue());
cd.setQuantity((new Integer(qty)).intValue());
return cd;
}
}
每次使用者在EShop.jsp中添加一件物品,請求都被發送到這個控制器servlet。它依次決定合適的動作,然後處理相應要添加的物品的請求參數。它就執行個體化一個新的CD bean(見清單4)代表這個選擇的物品,接著在把這個bean放進session之前處理購物車的更新。
清單4
CD.java
package shopping;
public class CD {
String album;
String artist;
String country;
float price;
int quantity;
public CD() {
album="";
artist="";
country="";
price=0;
quantity=0;
}
public void setAlbum(String title) {
album=title;
}
public String getAlbum() {
return album;
}
public void setArtist(String group) {
artist=group;
}
public String getArtist() {
return artist;
}
public void setCountry(String cty) {
country=cty;
}
public String getCountry() {
return country;
}
public void setPrice(float p) {
price=p;
}
public float getPrice() {
return price;
}
public void setQuantity(int q) {
quantity=q;
}
public int getQuantity() {
return quantity;
}
}
<html>
<body>
<h1>
Sorry, there was an unrecoverable error! <br>
Please try <a href="/examples/jsp/shopping/EShop.jsp">again</a>.
</h1>
</body>
</html>
部署音樂無界
我假定你正在使用來自sun的最新版本的JavaServer Web Development Kit (JSWDK)來運行這個例子。如果不是,參看資源小節去看看到哪裡取得它。假設伺服器安裝在\jswdk-1.0.1,這是Microsoft Windows系統下的預設路徑,可以象下面這樣部署音樂無界應用:
Create shopping directory under \jswdk-1.0.1\examples\jsp
Copy EShop.jsp to \jswdk-1.0.1\examples\jsp\shopping
Copy Cart.jsp to \jswdk-1.0.1\examples\jsp\shopping
Copy Checkout.jsp to \jswdk-1.0.1\examples\jsp\shopping
Compile the .java files by typing javac *.java
Copy ShoppingServlet.class to \jswdk-1.0.1\webpages\Web-Inf\servlets
Create shopping directory under \jswdk-1.0.1\examples\Web-Inf\jsp\beans
Copy CD.class to \jswdk-1.0.1\examples\Web-Inf\jsp\beans\shopping
Copy error.html to \jswdk-1.0.1\webpages
Once your server has been started, you should be able to access the application using http://localhost:8080/examples/jsp/shopping/EShop.jsp as the URL
只要你的伺服器啟動,你應該可以使用URL http://localhost:8080/examples/jsp/shopping/EShop.jsp來訪問這個應用程式。