实例讲解JSP Model2体系结构(中)

理解“音乐无国界”
“音乐无国界”的主界面是JSP页 Eshop.jsp(见代码清单1)。你会注意到,这个页面几乎只作为专门的用户界面,不承担任何处理任务――是一个最理想的JSP方案。另外,请注意另一个JSP页Cart.jsp(见代码清单2)被Eshop.jsp通过指令

1<jsp:include flush="true" page="Cart.jsp"></jsp:include>

包含于其中。

代码清单 1:EShop.jsp

1@ page session="true" 
 1<html>
 2<head>
 3<title>Music Without Borders</title>
 4</head>
 5<body bgcolor="#33CCFF">
 6<font face="Times New Roman,Times" size="+3">   
 7  
 8Music Without Borders   
 9  
10</font>
11<hr/><p>
12<center>
13<form action="/examples/servlet/ShoppingServlet" method="POST" name="shoppingForm">
14<b>CD:</b>
15<select name="CD">
16<option>Yuan | The Guo Brothers | China | $14.95</option>
17<option>Drums of Passion | Babatunde Olatunji | Nigeria | $16.95</option>
18<option>Kaira | Tounami Diabate| Mali | $16.95</option>
19<option>The Lion is Loose | Eliades Ochoa | Cuba | $13.95</option>
20<option>Dance the Devil Away | Outback | Australia | $14.95</option>
21<option>Record of Changes | Samulnori | Korea | $12.95</option>
22<option>Djelika | Tounami Diabate | Mali | $14.95</option>
23<option>Rapture | Nusrat Fateh Ali Khan | Pakistan | $12.95</option>
24<option>Cesaria Evora | Cesaria Evora | Cape Verde | $16.95</option>
25<option>Ibuki | Kodo | Japan | $13.95</option>
26</select>
27<b>Quantity: </b><input name="qty" size="3" type="text" value="1"/>
28<input name="action" type="hidden" value="ADD"/>
29<input name="Submit" type="submit" value="Add to Cart"/>
30</form>
31</center>
32<p>
33<jsp:include flush="true" page="Cart.jsp"></jsp:include>
34</p></p></body>
35</html>

代码清单 2:Cart.jsp

1@ page session="true" import="java.util.*, shopping.CD" 
1   
2  
3Vector buylist = (Vector) session.getValue("shopping.shoppingcart");   
4  
5if (buylist != null && (buylist.size() > 0)) {   
6  
 1<center>
 2<table bgcolor="#FFFFFF" border="0" cellpadding="0" width="100%">
 3<tr>
 4<td><b>ALBUM</b></td>
 5<td><b>ARTIST</b></td>
 6<td><b>COUNTRY</b></td>
 7<td><b>PRICE</b></td>
 8<td><b>QUANTITY</b></td>
 9<td></td>
10</tr>   
11  

for (int index=0; index &lt; buylist.size();index++) {

CD anOrder = (CD) buylist.elementAt(index);

 1  
 2<tr>
 3<td><b>```
 4= anOrder.getAlbum() 
 5```</b></td>
 6<td><b>```
 7= anOrder.getArtist() 
 8```</b></td>
 9<td><b>```
10= anOrder.getCountry() 
11```</b></td>
12<td><b>```
13= anOrder.getPrice() 
14```</b></td>
15<td><b>```
16= anOrder.getQuantity() 
17```</b></td>
18<td>
19<form action="/examples/servlet/ShoppingServlet" method="POST" name="deleteForm">
20<input type="submit" value="Delete"/>
21<input name="delindex" type="hidden" value="```
22= index 
23```"/>
24<input name="action" type="hidden" value="DELETE"/>
25</form>
26</td>
27</tr>   
28  

}

1  
2</table>
3<p>
4<form action="/examples/servlet/ShoppingServlet" method="POST" name="checkoutForm">
5<input name="action" type="hidden" value="CHECKOUT"/>
6<input name="Checkout" type="submit" value="Checkout"/>
7</form>
8</p></center>
1 } 

这里,Cart.jsp操纵着基于会话的购物车的表达,在MVC体系中,购物车就充当Model的角色。

观察Cart.jsp开头处的脚本片段:

1   
2  
3Vector buylist = (Vector) session.getValue("shopping.shoppingcart");   
4  
5if (buylist != null && (buylist.size() > 0)) {   
6  

这段脚本主要是从会话中取出购物车。如果购物车是空的或尚未创建,则它什么都不显示;因此,当用户第一次访问这个应用程序时,呈现给他的视图如图3所示:

图3:音乐无国界,主视图

图中按钮文字:放入购物车

如果购物车不为空,则选中的物品被依次从购物车中取出,如下面的脚本片段所示:

1   
2  
3for (int index=0; index < buylist.size(); index++) {   
4  
5CD anOrder = (CD) buylist.elementAt(index);   
6  

描述物品的变量一旦被创建,就会被用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;

}

}

Published At
Categories with Web编程
Tagged with
comments powered by Disqus