实例讲解JSP Model2体系结构(下)
实例讲解JSP Model2体系结构(下),实例讲解JSP Model2体系结构(下)
代码清单 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;
}
}
注意:我们在servlet中包括了附加的智能,这样一来它就能明白,如果一个原先加入过的CD被再次选中,它只需在购物车中为这个CD Bean增加计数就可以了。这个控制servlet也能处理在Cart.jsp中被触发的动作,比如用户从购物车中删除物品或结帐。注意观察,控制servlet一直在完全掌握着对资源的支配权,它决定在对特定动作的响应中调用哪些资源。例如,购物车状态的改动,如添加或删除,会使控制servlet把处理过的请求送至Eshop.jsp页。这促使该页重新显示主视图,这时购物车中显示的数据已被更新。如果用户决定结帐,这个请求在处理后被送至Checkout.jsp页(见代码清单5),通过如下所示的调度程序实现:
String url="/jsp/shopping/Checkout.jsp";
ServletContext sc = getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher(url);
rd.forward(req,res);
代码清单5:Checkout.jsp
<%@ page session="true" import="java.util.*, shopping.CD" %
<html
<head
<titleMusic Without Borders Checkout</title
</head
<body bgcolor="#33CCFF"
<font face="Times New Roman,Times" size=+3
Music Without Borders Checkout
</font
<hr<p
<center
<table border="0" cellpadding="0" width="100%" bgcolor="#FFFFFF"
<tr
<td<bALBUM</b</td
<td<bARTIST</b</td
<td<bCOUNTRY</b</td
<td<bPRICE</b</td
<td<bQUANTITY</b</td
<td</td
</tr
<%
Vector buylist = (Vector) session.getValue("shopping.shoppingcart");
String amount = (String) request.getAttribute("amount");
for (int i=0; i < buylist.size();i++) {
CD anOrder = (CD) buylist.elementAt(i);
%
<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