案例講解JSP Model2體系結(jié)構(gòu)(中)
發(fā)表時(shí)間:2024-01-02 來(lái)源:明輝站整理相關(guān)軟件相關(guān)文章人氣:
[摘要]理解“音樂(lè)無(wú)國(guó)界” “音樂(lè)無(wú)國(guó)界”的主界面是JSP頁(yè) Eshop.jsp(見(jiàn)代碼清單1)。你會(huì)注意到,這個(gè)頁(yè)面幾乎只作為專門的用戶界面,不承擔(dān)任何處理任務(wù)――是一個(gè)最理想的JSP方案。另外,請(qǐng)注意另一個(gè)JSP頁(yè)Cart.jsp(見(jiàn)代碼清單2)被Eshop.jsp通過(guò)指令<jsp:incl...
理解“音樂(lè)無(wú)國(guó)界”
“音樂(lè)無(wú)國(guó)界”的主界面是JSP頁(yè) Eshop.jsp(見(jiàn)代碼清單1)。你會(huì)注意到,這個(gè)頁(yè)面幾乎只作為專門的用戶界面,不承擔(dān)任何處理任務(wù)――是一個(gè)最理想的JSP方案。另外,請(qǐng)注意另一個(gè)JSP頁(yè)Cart.jsp(見(jiàn)代碼清單2)被Eshop.jsp通過(guò)指令<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操縱著基于會(huì)話的購(gòu)物車的表達(dá),在MVC體系中,購(gòu)物車就充當(dāng)Model的角色。
觀察Cart.jsp開(kāi)頭處的腳本片段:
<%
Vector buylist = (Vector) session.getValue("shopping.shoppingcart");
if (buylist != null && (buylist.size() > 0)) {
%>
這段腳本主要是從會(huì)話中取出購(gòu)物車。如果購(gòu)物車是空的或尚未創(chuàng)建,則它什么都不顯示;因此,當(dāng)用戶第一次訪問(wèn)這個(gè)應(yīng)用程序時(shí),呈現(xiàn)給他的視圖如圖3所示:
圖3:音樂(lè)無(wú)國(guó)界,主視圖
圖中按鈕文字:放入購(gòu)物車
如果購(gòu)物車不為空,則選中的物品被依次從購(gòu)物車中取出,如下面的腳本片段所示:
<%
for (int index=0; index < buylist.size(); index++) {
CD anOrder = (CD) buylist.elementAt(index);
%>
描述物品的變量一旦被創(chuàng)建,就會(huì)被用JSP表達(dá)式直接嵌入靜態(tài)HTML模板中去。圖4顯示了當(dāng)用戶向購(gòu)物車中放入一些物品后的視圖。
圖4:音樂(lè)無(wú)國(guó)界,購(gòu)物車視圖
圖中文字:Music Without Borders:音樂(lè)無(wú)國(guó)界;Quantity:數(shù)量;ALBUM:唱片;ARTIST:演唱者;COUNTRY:國(guó)家;PRICE:價(jià)格;Delete:刪除;Checkout:結(jié)帳。
這里需要注意的重要一點(diǎn)是,在Eshop.jsp和Cart.jsp中實(shí)現(xiàn)的對(duì)所有動(dòng)作的處理都由一個(gè)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")) {
//以前是否購(gòu)買了同樣的cd?
boolean match=false;
CD aCD = getCD(req);
if (buylist==null) {
//將第一張CD放入購(gòu)物車
buylist = new Vector(); //第一份定單
buylist.addElement(aCD);
} else { // 不是第一次購(gòu)買
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結(jié)束
} // for循環(huán)結(jié)束
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) {
//想象一下如果這些都在一個(gè)腳本片段中會(huì)有多么難看
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;
}
}