理解“音樂無國界”
“音樂無國界”的主界面是JSP頁 Eshop.jsp(見代碼清單1)。你會注意到,這個頁面幾乎只作為專門的用戶界面,不承擔任何處理任務――是一個最理想的JSP方案。另外,請注意另一個JSP頁Cart.jsp(見代碼清單2)被Eshop.jsp通過指令<jsp:include page="Cart.jsp" flush="true" />包含於其中。
代碼清單 1:EShop.jsp
<%@ page session="true" %>
<html>
<head>
<title>Music Without Borders</title>
</head>
<body bgcolor="#33CCFF">
<font face="Times New Roman,Times" size="+3">
Music Without Borders
</font>
<hr><p>
<center>
<form name="shoppingForm"
action="/examples/servlet/ShoppingServlet"
method="POST">
<b>CD:</b>
<select name=CD>
<option>Yuan | The Guo Brothers | China | $14.95</option>
<option>Drums of Passion | Babatunde Olatunji | Nigeria | $16.95</option>
<option>Kaira | Tounami Diabate| Mali | $16.95</option>
<option>The Lion is Loose | Eliades Ochoa | Cuba | $13.95</option>
<option>Dance the Devil Away | Outback | Australia | $14.95</option>
<option>Record of Changes | Samulnori | Korea | $12.95</option>
<option>Djelika | Tounami Diabate | Mali | $14.95</option>
<option>Rapture | Nusrat Fateh Ali Khan | Pakistan | $12.95</option>
<option>Cesaria Evora | Cesaria Evora | Cape Verde | $16.95</option>
<option>Ibuki | Kodo | Japan | $13.95</option>
</select>
<b>Quantity: </b><input type="text" name="qty" SIZE="3" value=1>
<input type="hidden" name="action" value="ADD">
<input type="submit" name="Submit" value="Add to Cart">
</form>
</center>
<p>
<jsp:include page="Cart.jsp" flush="true" />
</body>
</html>
代碼清單 2:Cart.jsp
<%@ page session="true" import="java.util.*, shopping.CD" %>
<%
Vector buylist = (Vector) session.getValue("shopping.shoppingcart");
if (buylist != null && (buylist.size() > 0)) {
%>
<center>
<table border="0" cellpadding="0" width="100%" bgcolor="#FFFFFF">
<tr>
<td><b>ALBUM</b></td>
<td><b>ARTIST</b></td>
<td><b>COUNTRY</b></td>
<td><b>PRICE</b></td>
<td><b>QUANTITY</b></td>
<td></td>
</tr>
<%
for (int index=0; index < buylist.size();index++) {
CD anOrder = (CD) buylist.elementAt(index);
%>
<tr>
<td><b><%= anOrder.getAlbum() %></b></td>
<td><b><%= anOrder.getArtist() %></b></td>
<td><b><%= anOrder.getCountry() %></b></td>
<td><b><%= anOrder.getPrice() %></b></td>
<td><b><%= anOrder.getQuantity() %></b></td>
<td>
<form name="deleteForm"
action="/examples/servlet/ShoppingServlet"
method="POST">
<input type="submit" value="Delete">
<input type="hidden" name= "delindex" value='<%= index %>'>
<input type="hidden" name="action" value="DELETE">
</form>
</td>
</tr>
<% } %>
</table>
<p>
<form name="checkoutForm"
action="/examples/servlet/ShoppingServlet"
method="POST">
<input type="hidden" name="action" value="CHECKOUT">
<input type="submit" name="Checkout" value="Checkout">
</form>
</center>
<% } %>
這裡,Cart.jsp操縱著基於會話的購物車的表達,在MVC體系中,購物車就充當Model的角色。
觀察Cart.jsp開頭處的腳本片段:
<%
Vector buylist = (Vector) session.getValue("shopping.shoppingcart");
if (buylist != null && (buylist.size() > 0)) {
%>
這段腳本主要是從會話中取出購物車。如果購物車是空的或尚未創建,則它什麼都不顯示;因此,當用戶第一次訪問這個應用程序時,呈現給他的視圖如圖3所示:
圖3:音樂無國界,主視圖
圖中按鈕文字:放入購物車
如果購物車不為空,則選中的物品被依次從購物車中取出,如下面的腳本片段所示:
<%
for (int index=0; index < buylist.size(); index++) {
CD anOrder = (CD) buylist.elementAt(index);
%>
描述物品的變量一旦被創建,就會被用JSP表達式直接嵌入靜態HTML模板中去。圖4顯示了當用戶向購物車中放入一些物品後的視圖。
圖4:音樂無國界,購物車視圖
圖中文字:Music Without Borders:音樂無國界;Quantity:數量;ALBUM:唱片;ARTIST:演唱者;COUNTRY:國家;PRICE:價格;Delete:刪除;Checkout:結帳。
這裡需要注意的重要一點是,在Eshop.jsp和Cart.jsp中實現的對所有動作的處理都由一個servlet――ShoppingServlet.java控制,如代碼清單3所示:
代碼清單3:ShoppingServlet.java
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")) {
//以前是否購買了同樣的cd?
boolean match=false;
CD aCD = getCD(req);
if (buylist==null) {
//將第一張CD放入購物車
buylist = new Vector(); //第一份定單
buylist.addElement(aCD);
} else { // 不是第一次購買
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;
} //if name matches結束
} // 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) {
//想象一下如果這些都在一個腳本片段中會有多麼難看
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;
}
}