使用MongoDB和JSP實現(xiàn)一個簡單的購物車系統(tǒng)實例
本文介紹了JSP編程技術實現(xiàn)一個簡單的購物車程序,具體如下:
1 問題描述
利用JSP編程技術實現(xiàn)一個簡單的購物車程序,具體要求如下。
(1)用JSP編寫一個登錄頁面,登錄信息中有用戶名和密碼,分別用兩個按鈕來提交和重置登錄信息。
(2)編寫一個JSP程序來獲取用戶提交的登錄信息并查詢數(shù)據庫,如果用戶名為本小組成員的名字且密碼為對應的學號時,采用JSP內置對象的方法跳轉到訂購頁面(顯示店中商品的種類和單價等目錄信息);否則采用JSP動作提示用戶重新登錄(注:此頁面上要包含前面的登錄界面)。
(3)當顧客填好所需商品的數(shù)量并點擊提交按鈕時,將前面訂購的商品放入購物車中并顯示購物車里的相關信息,包括商品的名稱和數(shù)量以及所有商品的總價格。
(4)將商品信息寫入數(shù)據庫,計算價格時通過查找數(shù)據庫來完成。
以下功能選做:
(5) 實現(xiàn)一個簡單的注冊功能,使新用戶能夠將自己的信息(姓名和學號)寫進數(shù)據庫,以供后面登錄時使用
(6)將數(shù)據庫的相關操作改寫成一個JavaBean
2 解決方案
2.1 實現(xiàn)功能
(1)用戶登錄。(通過查詢MongoDB數(shù)據庫,完成登錄認證)
(2)用戶注冊。(通過寫入MongoDB數(shù)據庫,完成用戶注冊)
(3)記住密碼。(通過使用Cookie,實現(xiàn)記住首頁用戶名和密碼功能)
(4)查看商品。(通過查詢MongoDB數(shù)據庫,返回商品具體信息,并顯示在客戶端界面)
(5)購買商品。
(6)購物車。(顯示用戶購買商品具體信息,刪除已購買商品或添加已購買商品數(shù)量,計算用戶當前購買商品總價格)
2.2 最終運行效果圖
2.3 系統(tǒng)功能框架示意圖
圖一:系統(tǒng)功能框架示例圖
具體解釋:
(1)瀏覽器中打開首頁login.jsp用戶登錄頁面;
(2)點擊創(chuàng)建新用戶按鈕,進入register.jsp用戶注冊頁面;
(3)注冊失敗則停留在register.jsp原頁面;注冊成功則跳轉到register_success.jsp注冊成功提示頁面,點擊返回按鈕,返回到登陸首頁login.jsp頁面;
(4)在首頁login.jsp頁面輸入用戶名和密碼,請求發(fā)送到login_action.jsp登陸處理腳本頁,數(shù)據匹配成功跳轉到welcome.jsp購物首頁頁面,否則跳轉到登陸視頻login_Fail.jsp頁面;
(5)進入welcome.jsp購物首頁頁面后,點擊下一頁和上一頁按鈕,可以查看當前商品信息;同一商品點擊一次購買按鈕實現(xiàn)購買一件商品,點擊多次則實現(xiàn)購買多件商品;點擊查看購物車按鈕,實現(xiàn)內部跳轉到Cart.jsp購物車頁面,可以產看當前購買商品編號、名稱、價格、購買數(shù)目以及所有商品總價格信息,并提供刪除已購買商品和添加已購買商品數(shù)目功能;
(6)購物首頁welcom.jsp頁面由header.jsp、main_shop.jsp、bottom.jsp三個頁面組成,具體如下圖二所示:
圖二:購物首頁welcome.jsp頁面
2.4 有關MongoDB簡介及系統(tǒng)環(huán)境配置
MongoDB是NoSQL家族的一員,和當前普遍使用的關系型數(shù)據庫(例如,mysql、SQLserver等)相比來說,舍棄了其中復雜的關系及實體間的關聯(lián)。換句話說,MongoDB是一種文檔型數(shù)據庫,就和我們日常寫文檔一樣,不用去擔心各類文檔的具體內容也不用仔細分類整理,均可以存放在自己電腦的硬盤里。下面請看一張MongoDB與關系型數(shù)據庫名詞概念對照表:
|
關系型數(shù)據庫 |
MongoDB |
|
database(數(shù)據庫) |
database(數(shù)據庫) |
|
table(表) |
collection(集合) |
|
row(行) |
document(文檔) |
|
column(列) |
filed(域) |
|
index(索引) |
index(索引) |
|
table joins(表關系) |
無 |
|
primary key(主鍵) |
自動將_id字段設置為主鍵 |
由上表可知,在我們熟悉的關系型數(shù)據庫中,具體的實體表對應MongoDB中的集合,表中的行對應MongoDB集合中的文檔,表中的列對應MongoDB文檔中的域,最關鍵的主鍵在MongoDB中是系統(tǒng)自動生成,MongoDB自動的生成的主鍵是按照特定的方法來生成,具體有12個字節(jié),12字節(jié)按照如下方式生成:
0|1|2|3 | 4|5|6 | 7|8 | 9|10|11
時間戳 | 機器 | PID | 計數(shù)器
以上是個人初步學習MongoDB的介紹,如有錯誤,歡迎各位圓友指正。
說完了概念,就要到具體運用,MongoDB中存入和讀取的數(shù)據格式均為BSON格式,BSON格式是一種類似JSON格式的數(shù)據,其具體樣式如下所示:
/* 7 createdAt:2016/11/22 下午3:52:51*/
{
"_id" : ObjectId("5833f953e9d60125601a8c8b"),
"sid" : "7",
"sname" : "紅米Note4",
"sprice" : "899"
},
/* 8 createdAt:2016/11/22 下午3:53:19*/
{
"_id" : ObjectId("5833f96fe9d60125601a8c8c"),
"sid" : "8",
"sname" : "平凡的世界",
"sprice" : "99"
},
/* 9 createdAt:2016/11/22 下午3:53:43*/
{
"_id" : ObjectId("5833f987e9d60125601a8c8d"),
"sid" : "9",
"sname" : "斗羅大陸",
"sprice" : "199"
},
當我們從MongoDB數(shù)據庫查詢獲取數(shù)據后,其格式為BSON格式,不能直接與客戶端獲取的數(shù)據進行匹配。在這里,我在獲取數(shù)據庫中BSON格式數(shù)據后,調用MongoDB驅動包中BSON.toMap()方法,把BSON格式轉換為Map鍵值對格式的字符串,然后調用Map中Map.get(“name”)方法,獲取其中具體鍵值對的值,從而實現(xiàn)與客戶端頁面中數(shù)據的匹配。
最后,最關鍵的一點就是,在新建項目中導入MongoDB驅動包,方便客戶端和業(yè)務層操作數(shù)據庫。這里我使用的是mongo-java-driver-3.3.0.jar包,其各版本驅動包下載鏈接:http://central.maven.org/maven2/org/mongodb/mongo-java-driver/
2.5 核心功能代碼講解
(1)用戶登錄功能
實現(xiàn)用戶登錄,主要是由login_action.jsp腳本中代碼來實現(xiàn),代碼中已給出具體注釋,具體如下:
<%@ page language="java" import="java.util.*,com.mongodb.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'login_action.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<%
response.setContentType("text/html;charset=utf-8"); //確保顯示的漢字信息以正確編碼方式顯示
request.setCharacterEncoding("utf-8"); //確保獲取的漢字信息以正確編碼方法獲取
String userName=(String)request.getParameter("username"); //獲取登錄頁面用戶名
String passWord=(String)request.getParameter("password");//獲取登陸頁面密碼
String checkBox = request.getParameter("save_password");//獲取登陸頁面記住密碼選擇框屬性值
boolean login_test = false; //設定登陸布爾值,若用戶名和密碼成功匹配,則為true
try{
// 連接到 mongodb 服務
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
//此處采用無用戶名和密碼驗證方式登陸
@SuppressWarnings("deprecation")
DB db = mongoClient.getDB( "library" ); //連接到數(shù)據庫library
DBCollection coll = db.getCollection("userInfo"); //獲取library數(shù)據庫中集合userInfo
System.out.println("Collection userInfo selected successfully");
DBCursor cursor = coll.find(); //查詢集合userInfo中文檔信息
int i=1;
while (cursor.hasNext()) { //檢索集合userInfo中所有文檔信息
System.out.println("userInfo Document: "+i);
DBObject show = cursor.next();
System.out.println(show);
@SuppressWarnings("rawtypes")
Map show1 = show.toMap(); //將檢索結果show(Bson類型)轉換為Map類型
String toname = (String)show1.get("username"); //提取Map中字段名為username的屬性值
String topassword = (String)show1.get("password"); //提取Map中字段名為password的屬性值
if(toname.equals(userName) && topassword.equals(passWord)){
//將從數(shù)據庫中獲取的用戶名和密碼與表單中獲取的數(shù)據進行驗證,匹配成功則使login_test值為true
System.out.println("登陸成功?。。。。?+"username:"+toname+" password:"+topassword);
//request.getRequestDispatcher("welcome.jsp").forward(request, response);
login_test = true;
}
System.out.println(show1.get("username"));
i++;
}
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
if(login_test) {
if ("save".equals(checkBox)) {
//Cookie存取時用URLEncoder.encode進行編碼(PS:讀取時URLDecoder.decode進行解碼)
String name1 = java.net.URLEncoder.encode(userName,"UTF-8");
//創(chuàng)建兩個Cookie對象
Cookie nameCookie = new Cookie("username", name1);
//設置Cookie的有效期為3天
nameCookie.setMaxAge(60 * 60 * 24 * 3);
String pwd = java.net.URLEncoder.encode(passWord,"UTF-8");
Cookie pwdCookie = new Cookie("password", pwd);
pwdCookie.setMaxAge(60 * 60 * 24 * 3);
response.addCookie(nameCookie);
response.addCookie(pwdCookie);
}
// request.getRequestDispatcher("welcome.jsp").forward(request, response);
response.sendRedirect("welcome.jsp");
}
else{
response.sendRedirect("login_Fail.jsp");
// request.getRequestDispatcher("loginFail.jsp").forward(request, response);
}
%>
</body>
</html>
(2)用戶注冊功能
用戶注冊功能實現(xiàn)原理基本和用戶登錄一致,唯一的區(qū)別在于用戶登錄是查詢數(shù)據庫,而用戶注冊是寫入數(shù)據庫,此處就不貼具體代碼,在下面具體編碼中展示。
(3)記住密碼功能
實現(xiàn)記住密碼,此處使用兩個Cookie,當用戶正確登錄時,Cookie_one獲取用戶名,并添加到當前瀏覽器Cookie中,Cookie_two獲取密碼,也添加到當前瀏覽器Cookie中。在登錄首頁用戶名和密碼兩個輸入框中的value值填寫系統(tǒng)從Cookie中獲取的用戶名和密碼,從而實現(xiàn)記住密碼功能。具體如下:
if(login_test) {
if ("save".equals(checkBox)) {
//Cookie存取時用URLEncoder.encode進行編碼(PS:讀取時URLDecoder.decode進行解碼)
String name1 = java.net.URLEncoder.encode(userName,"UTF-8");
//創(chuàng)建兩個Cookie對象
Cookie nameCookie = new Cookie("username", name1);
//設置Cookie的有效期為3天
nameCookie.setMaxAge(60 * 60 * 24 * 3);
String pwd = java.net.URLEncoder.encode(passWord,"UTF-8");
Cookie pwdCookie = new Cookie("password", pwd);
pwdCookie.setMaxAge(60 * 60 * 24 * 3);
response.addCookie(nameCookie);
response.addCookie(pwdCookie);
}
// request.getRequestDispatcher("welcome.jsp").forward(request, response);
response.sendRedirect("welcome.jsp");
}
else{
response.sendRedirect("login_Fail.jsp");
// request.getRequestDispatcher("loginFail.jsp").forward(request, response);
}
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
String username = "";
String password = "";
//獲取當前站點的所有Cookie
Cookie[] cookies = request.getCookies();
for (int i = 0; i < cookies.length; i++) {
//對cookies中的數(shù)據進行遍歷,找到用戶名、密碼的數(shù)據
if ("username".equals(cookies[i].getName())) {
//讀取時URLDecoder.decode進行解碼(PS:Cookie存取時用URLEncoder.encode進行編碼)
username = java.net.URLDecoder.decode(cookies[i].getValue(),"UTF-8");
} else if ("password".equals(cookies[i].getName())) {
password = java.net.URLDecoder.decode(cookies[i].getValue(),"UTF-8");
}
}
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>登陸頁面</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta http-equiv="description" content="This is my page">
<link rel="stylesheet" type="text/css" href="css/login.css">
</head>
<body>
<div class="content">
<div class="head">
<h1>簡單購物車</h1>
</div>
<!-- 登錄面板 -->
<div class="panel">
<form action="login_action.jsp" method="post">
<!-- 賬號和密碼組 -->
<div class="group">
<label>賬號</label>
<input type="text" placeholder="請輸入賬號" name="username" value="<%=username%>">
</div>
<div class="group">
<label>密碼</label>
<input type="password" placeholder="請輸入密碼" name="password" value="<%=password%>">
</div>
<div>
<input type="checkbox" value="save" name="save_password">
<label>記住密碼</label>
</div>
<div class="group">
<label></label>
</div>
<!-- 登錄按鈕 -->
<div class="login">
<button type="submit" name="login">登陸</button>
<button type="reset" name="reset">重置</button>
</div>
</form>
</div>
<!-- 注冊按鈕 -->
<div class="register">
<button onclick="window.location.href='register.jsp'">創(chuàng)建新賬號</button>
</div>
</div>
</body>
</html>
(4)查詢商品和購買商品
此處功能主要是操作MongoDB數(shù)據庫,返回商品的具體信息,只要弄懂用戶登錄功能后,此處的功能代碼就會很快弄明白,具體代碼在后面展示。
(5)購物車
此處的功能也是主要操作MongoDB數(shù)據,通過和客戶端的用戶交互,實現(xiàn)購物車相關功能,具體代碼在后面展示。
2.6 具體編碼
具體編碼的講解,就按照實現(xiàn)功能大致順序來介紹,具體如下:
2.6.1用戶登錄和記住密碼
首先看是登錄首頁login.jsp頁面,為了顯示美觀,此物使用一個login.css文件(后面多個頁面均是使用login.css文件)。login.css具體代碼如下:
@CHARSET "UTF-8";
/*按照樣圖要求,添加一個淺灰色背景*/
body{
background-color: #F2F2F2;
}
/*設置內容模塊距離頂部一個有一段距離100px*/
.content {
margin-top: 80px;
}
/*登錄和注冊按鈕的整體樣式*/
.content button {
height: 30px;/*登錄和注冊按鈕的高度*/
color: white;/*登錄和注冊按鈕字體顏色為白色*/
font-size: 18px;/*登錄和注冊按鈕的字體大小*/
border: 0px;/*無邊框*/
padding: 0px;/*無內邊距*/
cursor: pointer;/*登錄和注冊按鈕的選擇時為手形狀*/
}
/*頭部名稱*/
.content .head {
text-align: center;/*子內容居中*/
}
/*登錄面板*/
.content .panel {
background-color: white;/*登錄面板背景顏色為白色*/
width: 302px;/*寬度為302px*/
text-align: center;/*子內容居中*/
margin: 0px auto;/*自身居中*/
padding-top: 10px;/*頂部的內邊距為20px*/
padding-bottom: 10px;/*底部的內邊距為20px*/
border: 1px solid #ddd;/*邊框顏色為灰色*/
border-radius: 5px;/*邊框邊角有5px的弧度*/
}
/*購物主頁購物面板*/
.content .panel1 {
background-color: white;/*購物主頁面板背景顏色為白色*/
width: 1000px;/*寬度為600px*/
text-align: center;/*子內容居中*/
margin: 0px auto;/*自身居中*/
border: 1px solid #ddd;/*邊框顏色為灰色*/
border-radius: 5px;/*邊框邊角有5px的弧度*/
}
/*登錄和密碼組*/
.content .panel .group {
text-align: left;/*子內容居中*/
width: 262px;/*寬度為262px*/
margin: 0px auto 20px;/*自身居中,并距離底部有20px的間距*/
}
.content .panel .group label {
line-height: 30px;/*高度為30px*/
font-size: 18px;/*字體大小為18px*/
}
.content .panel .group input {
display: block;/*設置為塊,是為了讓輸入框獨占一行*/
width: 250px;/*寬度為250px*/
height: 30px;/*高度為30px*/
border: 1px solid #ddd;/*輸入框的邊框*/
padding: 0px 0px 0px 10px;/*左邊內邊距為10px,顯得美觀*/
font-size: 16px;/*字體大小*/
}
.content .panel .group input:focus{
border-left: 1px solid #CC865E;/*當輸入框成為焦點時,左邊框顏色編程褐色*/
}
.content .panel .login button {
background-color: #CC865E;/*按鈕的背景顏色*/
width: 130px;/*按鈕的寬度*/
}
.content .panel .login button:hover {
background-color: white;/*按鈕選中后背景顏色為白色*/
color: #CC865E;/*按鈕選中后字體顏色為褐色*/
border: 1px solid #CC865E;/*按鈕選中后邊框顏色為褐色*/
}
/*注冊按鈕*/
.content .register {
text-align: center;/*子內容居中*/
margin-top: 20px;/*頂部的內邊距為20px*/
}
.content .register button {
background-color: #466BAF;/*按鈕的背景顏色為藍色*/
width: 180px;/*按鈕的寬度*/
}
.content .register button:hover {
background-color: white;/*按鈕選中后背景顏色為白色*/
color: #466BAF;/*按鈕選中后字體顏色為藍色*/
border: 1px solid #466BAF;/*按鈕選中后邊框顏色為藍色*/
}
Login.jsp具體代碼如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
String username = "";
String password = "";
//獲取當前站點的所有Cookie
Cookie[] cookies = request.getCookies();
for (int i = 0; i < cookies.length; i++) {
//對cookies中的數(shù)據進行遍歷,找到用戶名、密碼的數(shù)據
if ("username".equals(cookies[i].getName())) {
//讀取時URLDecoder.decode進行解碼(PS:Cookie存取時用URLEncoder.encode進行編碼)
username = java.net.URLDecoder.decode(cookies[i].getValue(),"UTF-8");
} else if ("password".equals(cookies[i].getName())) {
password = java.net.URLDecoder.decode(cookies[i].getValue(),"UTF-8");
}
}
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>登陸頁面</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta http-equiv="description" content="This is my page">
<link rel="stylesheet" type="text/css" href="css/login.css">
</head>
<body>
<div class="content">
<div class="head">
<h1>簡單購物車</h1>
</div>
<!-- 登錄面板 -->
<div class="panel">
<form action="login_action.jsp" method="post">
<!-- 賬號和密碼組 -->
<div class="group">
<label>賬號</label>
<input type="text" placeholder="請輸入賬號" name="username" value="<%=username%>">
</div>
<div class="group">
<label>密碼</label>
<input type="password" placeholder="請輸入密碼" name="password" value="<%=password%>">
</div>
<div>
<input type="checkbox" value="save" name="save_password">
<label>記住密碼</label>
</div>
<div class="group">
<label></label>
</div>
<!-- 登錄按鈕 -->
<div class="login">
<button type="submit" name="login">登陸</button>
<button type="reset" name="reset">重置</button>
</div>
</form>
</div>
<!-- 注冊按鈕 -->
<div class="register">
<button onclick="window.location.href='register.jsp'">創(chuàng)建新賬號</button>
</div>
</div>
</body>
</html>
登錄處理腳本login_action.jsp代碼如下:
<%@ page language="java" import="java.util.*,com.mongodb.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'login_action.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<%
response.setContentType("text/html;charset=utf-8"); //確保顯示的漢字信息以正確編碼方式顯示
request.setCharacterEncoding("utf-8"); //確保獲取的漢字信息以正確編碼方法獲取
String userName=(String)request.getParameter("username"); //獲取登錄頁面用戶名
String passWord=(String)request.getParameter("password");//獲取登陸頁面密碼
String checkBox = request.getParameter("save_password");//獲取登陸頁面記住密碼選擇框屬性值
boolean login_test = false; //設定登陸布爾值,若用戶名和密碼成功匹配,則為true
try{
// 連接到 mongodb 服務
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
//此處采用無用戶名和密碼驗證方式登陸
@SuppressWarnings("deprecation")
DB db = mongoClient.getDB( "library" ); //連接到數(shù)據庫library
DBCollection coll = db.getCollection("userInfo"); //獲取library數(shù)據庫中集合userInfo
System.out.println("Collection userInfo selected successfully");
DBCursor cursor = coll.find(); //查詢集合userInfo中文檔信息
int i=1;
while (cursor.hasNext()) { //檢索集合userInfo中所有文檔信息
System.out.println("userInfo Document: "+i);
DBObject show = cursor.next();
System.out.println(show);
@SuppressWarnings("rawtypes")
Map show1 = show.toMap(); //將檢索結果show(Bson類型)轉換為Map類型
String toname = (String)show1.get("username"); //提取Map中字段名為username的屬性值
String topassword = (String)show1.get("password"); //提取Map中字段名為password的屬性值
if(toname.equals(userName) && topassword.equals(passWord)){
//將從數(shù)據庫中獲取的用戶名和密碼與表單中獲取的數(shù)據進行驗證,匹配成功則使login_test值為true
System.out.println("登陸成功!?。。。?+"username:"+toname+" password:"+topassword);
//request.getRequestDispatcher("welcome.jsp").forward(request, response);
login_test = true;
}
System.out.println(show1.get("username"));
i++;
}
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
if(login_test) {
if ("save".equals(checkBox)) {
//Cookie存取時用URLEncoder.encode進行編碼(PS:讀取時URLDecoder.decode進行解碼)
String name1 = java.net.URLEncoder.encode(userName,"UTF-8");
//創(chuàng)建兩個Cookie對象
Cookie nameCookie = new Cookie("username", name1);
//設置Cookie的有效期為3天
nameCookie.setMaxAge(60 * 60 * 24 * 3);
String pwd = java.net.URLEncoder.encode(passWord,"UTF-8");
Cookie pwdCookie = new Cookie("password", pwd);
pwdCookie.setMaxAge(60 * 60 * 24 * 3);
response.addCookie(nameCookie);
response.addCookie(pwdCookie);
}
// request.getRequestDispatcher("welcome.jsp").forward(request, response);
response.sendRedirect("welcome.jsp");
}
else{
response.sendRedirect("login_Fail.jsp");
// request.getRequestDispatcher("loginFail.jsp").forward(request, response);
}
%>
</body>
</html>
登錄失敗login_Fail.jsp頁面代碼如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>登陸失敗</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<link rel="stylesheet" type="text/css" href="css/login.css">
</head>
<body>
<div class="content">
<div class="panel1">
<h1>輸入用戶名和密碼不正確,請重新登陸!??!</h1>
</div>
<div class="register">
<button onclick="window.location.href='login.jsp'">返回</button>
</div>
</div>
</body>
</html>
2.6.2用戶注冊
注冊首頁register.jsp頁面代碼如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>注冊頁面</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta http-equiv="description" content="This is my page">
<link rel="stylesheet" type="text/css" href="css/login.css">
<Script Language="JavaScript">
function check()
{
var tmp,str;
str=document.myform.password1.value;
tmp=document.myform.password2.value;
if(str != tmp)
alert("兩次密碼輸入不一致,請重新確認密碼?。。?);
}
</Script>
</head>
<body>
<div class="content">
<div class="head">
<h1>歡迎來到簡單購物車系統(tǒng)注冊頁面</h1>
</div>
<!-- 注冊面板 -->
<div class="panel">
<form name="myform" action="register_action.jsp" method="post">
<!-- 賬號和密碼組 -->
<div class="group">
<label></label>
<input type="text" placeholder="請輸入注冊賬號" name="username1">
</div>
<div class="group">
<label></label>
<input type="password" placeholder="請輸入注冊密碼" name="password1">
</div>
<div class="group">
<label></label>
<input type="password" placeholder="請確認注冊密碼" name="password2">
</div>
<!-- 注冊按鈕 -->
<div class="login">
<button type="submit" name="register" onclick="check()">注冊</button>
<button type="reset" name="reset1">重置</button>
</div>
</form>
<div class="register">
<button onclick="window.location.href='login.jsp'">返回</button>
</div>
</div>
</div>
</body>
</html>
注冊處理腳本register_action.jsp代碼如下;
<%@ page language="java" import="java.util.*,com.mongodb.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
String text_change = "等待注冊";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'register_action.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<%
response.setContentType("text/html;charset=utf-8"); //確保顯示的漢字信息以正確編碼方式顯示
request.setCharacterEncoding("utf-8"); //確保獲取的漢字信息以正確編碼方法獲取
String userName1=(String)request.getParameter("username1"); //獲取頁面用戶名
String passWord1=(String)request.getParameter("password1");//獲取注冊頁面密碼1
String passWord2=(String)request.getParameter("password2");//獲取注冊頁面密碼2
if(!passWord1.equals(passWord2)){
//如果用戶兩次輸入密碼不一致,則跳轉到注冊原頁面register.jsp,即實現(xiàn)未跳轉效果
response.sendRedirect("register.jsp");
}
try{
// 連接到 mongodb 服務
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
//此處采用無用戶名和密碼驗證方式登陸
@SuppressWarnings("deprecation")
DB db = mongoClient.getDB( "library" ); //連接到數(shù)據庫library
DBCollection coll = db.getCollection("userInfo"); //獲取library數(shù)據庫中集合userInfo
System.out.println("Collection userInfo selected successfully");
DBObject user = new BasicDBObject();//定義一個Bson變量,用于存儲注冊的用戶名和密碼
user.put("username", userName1);
user.put("password", passWord1);
coll.insert(user); //向集合userInfo中插入注冊用戶信息
response.sendRedirect("register_success.jsp"); //注冊成功后,自動跳轉到注冊成功提示頁面
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
%>
</body>
</html>
成功注冊提示頁面register_success.jsp頁面代碼如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>注冊成功</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<link rel="stylesheet" type="text/css" href="css/login.css">
</head>
<body>
<div class="content">
<div class="panel1">
<h1>恭喜您,您已經成功注冊簡單購物車系統(tǒng)</h1>
</div>
<div class="register">
<button onclick="window.location.href='login.jsp'">返回</button>
</div>
</div>
</body>
</html>
2.6.3查看商品
首先看一下購物首頁welcome.jsp頁面代碼:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>購物頁面</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <frameset rows="30%,60%,10%" cols="*" frameborder="no" border="0" framespacing="0"> <frame src="header.jsp"> <frame src="main_shop.jsp"> <frame src="bottom.jsp"> </frameset> <body> </body> </html>
首頁頭部header.jsp頁面代碼:
<%@ page language="java" import="java.util.*" contentType="text/html;charset=gb2312" pageEncoding="gb2312"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title></title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<meta http-equiv="Content-Type" content="text/html;charset=gb2312">
</head>
<body topmargin="0" leftmargin="0" rightmargin="0" style="background-color: #F2F2F2;overflow-x:hidden;overflow-y:hidden">
<form action="">
<table width="100%" height="79" border="0" cellpadding="0"
cellspacing="0" align=center>
<tr>
<td bgcolor="F9A859" valign="top">
<table width="100%" height="100" border="0" align="center"
cellpadding="0" cellspacing="0" bgcolor="#466BAF">
<tr>
<td align="center" style="font-size:60px;color: white;">
簡單購物車系統(tǒng)
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td bgcolor="F9A859" valign="top">
<table width="100%" height="50" border="0" align="center" cellpadding="0"
cellspacing="0" bgcolor="#CC865E">
<tr>
<td align="center" style="font-size:20px;color: white;">
歡迎你訪問!</td>
</tr>
</table>
</td>
</tr>
</table>
</form>
</body>
</html>
尾部bottom.jsp頁面代碼:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'bottom.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body style="background-color: #F2F2F2;overflow-x:hidden;overflow-y:hidden">
<hr>
<h4 style="width:100%;text-align:center">Copyright @2016 舞動的心</h4>
</body>
</html>
首頁中間主體main_shop.jsp頁面代碼;
<%@ page contentType="text/html;charset=GBK" import="java.util.*,com.liuzhen.shop.MongodbBean" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
String cp=request.getParameter("cp");//cp為分頁數(shù)
//int page_number = DBBean.getTotalPage();
//int currpage = page_number;
int currpage=(cp==null||cp=="")?1:Integer.parseInt(cp);
String[][] ss = MongodbBean.getGoodList(currpage);
int n = MongodbBean.getlength(ss);
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>購物頁面</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<link rel="stylesheet" type="text/css" href="css/login.css">
</head>
<body style="overflow-x:hidden;overflow-y:hidden">
<div class="content">
<div class="panel1">
<table border="1" align="center">
<tr>
<th width="30%" align="center">物品編號</th>
<th width="30%" align="center">物品名</th>
<th width="30%" align="center">定價</th>
<th width="50%" align="center">求購</th>
</tr>
<%
for(int i=0;i<n;i++)
{
%>
<tr>
<td height="30%" align="center"><%= ss[i][0] %></td>
<td height="30%" align="center"><%= ss[i][1] %></td>
<td height="30%" align="center"><%= ss[i][2] %></td>
<td height="30%" align="center"><a href="Buy.jsp?sid=<%= ss[i][0] %>&action=buy">購買</a></td>
</tr>
<%
}
%>
</table>
<%
int tp=MongodbBean.getTotalPage();
if(currpage!=1)
{
%>
<a href="main_shop.jsp?cp=<%=currpage-1%>">上一頁</a>
<%
}
if(currpage!=tp)
{
%>
<a href="main_shop.jsp?cp=<%=currpage+1%>">下一頁</a>
<%
}
%>
<form action="main_shop.jsp" name="myform">
<select name="cp" onchange="document.myform.submit()">
<%
for(int i=1;i<=tp;i++)
{
%>
<option value="<%=i%>" <%= (i==currpage)?"selected":"" %>>第<%=i%>頁</option>
<%
}
%>
</select>
</form>
</div>
<div class="register">
<button onclick="window.location.href='Cart.jsp'">查看購物車</button>
</div>
</div>
</body>
</html>
實現(xiàn)查看商品的功能,主要是通過調用MongodbBean.java類來實現(xiàn),其具體代碼如下:
package com.liuzhen.shop;
import java.util.Map;
import java.util.Vector;
import com.mongodb.*;
public class MongodbBean {
static int span=5; //設定JSP頁面表單單頁顯示物品信息行數(shù)為5行
//返回數(shù)據庫中全部貨物編號sid
public static String[] getGood_sid(){
String[] good_sid_temporary = new String[100]; //定義一個長度為100的暫時存放貨物編號的一維數(shù)組
// 連接到 mongodb 服務
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
//此處采用無用戶名和密碼驗證方式登陸
@SuppressWarnings("deprecation")
DB db = mongoClient.getDB( "library" ); //連接到數(shù)據庫library
DBCollection coll = db.getCollection("good"); //獲取library數(shù)據庫中集合good
System.out.println("Collection userInfo selected successfully");
DBCursor cursor = coll.find(); //查詢集合good中文檔信息
int i=0;
while (cursor.hasNext()) { //檢索集合good中所有文檔信息
DBObject show = cursor.next();
@SuppressWarnings("rawtypes")
Map show1 = show.toMap(); //將檢索結果show(Bson類型)轉換為Map類型
String tosid = (String)show1.get("sid"); //提取Map中字段名為sid的屬性值
good_sid_temporary[i] = tosid; //將數(shù)據庫中查詢的貨物編號存儲入數(shù)組good_sid
i++;
}
String[] good_sid = new String[i]; //根據查詢數(shù)據遍歷集合中文檔信息i值來確定最終返回數(shù)組長度
for(int j=0;j<i;j++){
good_sid[j] = good_sid_temporary[j];
}
return good_sid;
}
//返回數(shù)據庫中全部貨物名稱sname
public static String[] getGood_sname(){
String[] good_sname_temporary = new String[100]; //定義一個長度為100的暫時存放貨物名稱的一維數(shù)組
// 連接到 mongodb 服務
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
//此處采用無用戶名和密碼驗證方式登陸
@SuppressWarnings("deprecation")
DB db = mongoClient.getDB( "library" ); //連接到數(shù)據庫library
DBCollection coll = db.getCollection("good"); //獲取library數(shù)據庫中集合good
System.out.println("Collection userInfo selected successfully");
DBCursor cursor = coll.find(); //查詢集合good中文檔信息
int i=0;
while (cursor.hasNext()) { //檢索集合good中所有文檔信息
DBObject show = cursor.next();
@SuppressWarnings("rawtypes")
Map show1 = show.toMap(); //將檢索結果show(Bson類型)轉換為Map類型
String tosname = (String)show1.get("sname"); //提取Map中字段名為sname的屬性值
good_sname_temporary[i] = tosname; //將數(shù)據庫中查詢的貨物名稱存儲入數(shù)組good_sname
i++;
}
String[] good_sname = new String[i]; //根據查詢數(shù)據遍歷集合中文檔信息i值來確定最終返回數(shù)組長度
for(int j=0;j<i;j++){
good_sname[j] = good_sname_temporary[j];
}
return good_sname;
}
//返回數(shù)據庫中全部貨物價格sprice
public static String[] getGood_sprice(){
String[] good_sprice_temporary = new String[100]; //定義一個長度為100的暫時存放貨物價格的一維數(shù)組
// 連接到 mongodb 服務
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
//此處采用無用戶名和密碼驗證方式登陸
@SuppressWarnings("deprecation")
DB db = mongoClient.getDB( "library" ); //連接到數(shù)據庫library
DBCollection coll = db.getCollection("good"); //獲取library數(shù)據庫中集合good
System.out.println("Collection userInfo selected successfully");
DBCursor cursor = coll.find(); //查詢集合good中文檔信息
int i=0;
while (cursor.hasNext()) { //檢索集合good中所有文檔信息
DBObject show = cursor.next();
@SuppressWarnings("rawtypes")
Map show1 = show.toMap(); //將檢索結果show(Bson類型)轉換為Map類型
String tosprice = (String)show1.get("sprice"); //提取Map中字段名為sname的屬性值
good_sprice_temporary[i] = tosprice; //將數(shù)組庫中查詢的貨物價格存儲入數(shù)組good_sprice
i++;
}
String[] good_sprice = new String[i]; //根據查詢數(shù)據遍歷集合中文檔信息i值來確定最終返回數(shù)組長度
for(int j=0;j<i;j++){
good_sprice[j] = good_sprice_temporary[j];
}
return good_sprice;
}
//根據分頁當前page數(shù),從數(shù)據庫中獲取當前單個頁面貨物種類的具體信息,并以二維數(shù)據返回具體信息
public static String[][] getGoodList(int page)
{
String[][] result=null;
Vector<String[]> v=new Vector<String[]>(); //定義一個Vector集合,一個記錄存放一個貨物的具體信息
String[] good_sid = getGood_sid(); //獲取貨物編號
String[] good_sname = getGood_sname(); //獲取貨物名稱
String[] good_sprice = getGood_sprice(); //獲取貨物價格
int len = good_sid.length;
for(int i=0;i<span;i++){
int t = (page-1)*span+i; //獲取貨物編號
if(t >= len){
//如果當前貨物編號大于數(shù)據庫中已有編號,則跳出循環(huán)
break;
}
String[] good_temp=new String[3]; //定義一個長度為3的數(shù)組,用于存放一個物品的編號、名稱、價格信息
good_temp[0]=good_sid[t];
good_temp[1]=good_sname[t];
good_temp[2]=good_sprice[t];
v.add(good_temp); //將1個物品的信息存入Vector集合中
}
int size = v.size();
result=new String[size][]; //根據Vercotr大小,給result指定行數(shù)大小
for(int j=0;j<size;j++)
{
//返回Vector中一個值(其中即表示一個物品的sid,名稱和價格),并賦值給result[j],即result二維數(shù)組一行表示一個物品具體信息
result[j]=(String[])v.elementAt(j);
}
return result;
}
//根據貨物sid,返回其價格信息
public static double getPrice(String sid)
{
double price = 0; //定義返回物品的價格
String[] good_sprice = getGood_sprice(); //獲取全部物品的價格
int i = Integer.parseInt(sid); //將String類型的物品編號sid轉換為int型
String sprice = good_sprice[i]; //根據sid獲取物品的價格
price = Double.parseDouble(sprice); //將String類型的價格信息轉換為double型,并賦值給price
return price;
}
//根據貨物sid,返回貨物的名稱和價格,一一個長度為2的數(shù)組返回
public static String[] getDetail(String sid)
{
String[] good_detail=null;
good_detail = new String[2];
String[] good_sname = getGood_sname(); //獲取全部物品名稱
String[] good_sprice = getGood_sprice(); //獲取全部物品價格
int i = Integer.parseInt(sid); //將String類型的物品編號sid轉換為int型
good_detail[0] = good_sname[i]; //根據物品編號sid,得到名稱存入數(shù)組good_detail中
good_detail[1] = good_sprice[i]; //根據物品編號sid,得到物品價格存入數(shù)組good_detail中
return good_detail;
}
//通過查詢數(shù)據庫中貨物種類數(shù)目,以5行為一頁,返回現(xiàn)有貨物頁數(shù)
public static int getTotalPage()
{
int page = 0;
String[] good_sid = getGood_sid();
int len = good_sid.length;
page = len/span+((len%span==0)?0:1); //以span(span值為5)行為一頁,計算貨物具有的頁數(shù)page
return page;
}
//返回一個二維數(shù)組的行數(shù)大小
public static int getlength(String[][] a){
return a.length;
}
public static void main(String args[]){
// String[] good_sid = getGood_sid(); //定義一個存放貨物編號的一維數(shù)組
// String[] good_sname = getGood_sname(); //定義一個存放貨物名稱的一維數(shù)組
// String[] good_sprice = getGood_sprice(); //定義一個存放貨物價格的一維數(shù)組
//
// for(int j=0;j<10;j++){
// System.out.println("貨物sid:"+good_sid[j]);
// System.out.println("貨物sname:"+good_sname[j]);
// System.out.println("貨物是price:"+good_sprice[j]);
// System.out.println("**************************");
// System.out.println();
// }
System.out.println("分頁數(shù)目(測試):"+MongodbBean.getTotalPage());
String[][] ss=MongodbBean.getGoodList(MongodbBean.getTotalPage());
for(int i=0;i<ss.length;i++)
{
System.out.println(ss[i][0]);
System.out.println(ss[i][1]);
System.out.println(ss[i][2]);
System.out.println("***********");
}
int n = ss.length;
System.out.println("數(shù)組長度為:"+n);
}
}
2.6.4購買商品
實現(xiàn)購買商品,通過Buy.jsp業(yè)務處理腳本調用ShopCartBean.java類來實現(xiàn)。
ShopCartBean.java類代碼如下:
package com.liuzhen.shop;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
public class ShopCartBean {
//ShopCartBean類構造函數(shù)
public ShopCartBean(){
}
//定義一個存儲整形數(shù)值的鍵值對hashMap
HashMap<String, Integer> hm=new HashMap<String, Integer>();
//定義購物車總物品總價格,初始值為0
double total=0;
//添加購買的物品,存入哈希表hm中,并計算購買成功后的總價格
public void add(String sid)
{
if(hm.containsKey(sid))
{
//如果hm中包含鍵值對sid,則獲取該鍵值對中的值,并加1
int xc=((Integer)hm.get(sid)).intValue()+1;
//把上面獲取的xc值存入hm中
hm.put(sid,new Integer(xc));;
}
else
{
//如果hm中不包含鍵值對sid,則將該鍵值對存入hm中,并該鍵值對值為1
hm.put(sid,new Integer(1));
}
total=total+MongodbBean.getPrice(sid); //購買物品后,計算物品總價格
}
//獲取購物車當前物品總價格
public double getTotal()
{
return total;
}
//根據物品編號sid,設定購買物品數(shù)目,并將購買數(shù)目存入哈希表hm中,并更新當前購物車物品總價格
public void setCount(int c,String sid)
{
int yc=((Integer)hm.get(sid)).intValue();
total=total+(c-yc)*MongodbBean.getPrice(sid);
hm.put(sid,new Integer(c));
}
//根據物品編號sid,從購物車中刪除物品,并刪除存入哈希表hm中物品的數(shù)目,以及當前購物車物品總價格
public void deleteFromCart(String sid)
{
int yc=((Integer)hm.get(sid)).intValue();
total=total-yc*MongodbBean.getPrice(sid);
hm.remove(sid);
}
//判斷當前哈希表hm是否為空
public boolean isEmpty()
{
return hm.isEmpty();
}
//返回用戶購買物品的詳細信息(物品編號、物品名稱、物品價格、物品購買數(shù)量)
public String[][] getCart()
{
//定義一個set集合,存放哈希表hm中鍵值對的鍵名稱
Set<String> ks=hm.keySet();
//定義一個迭代器,用于遍歷set集合
Iterator<String> ii=ks.iterator();
//獲取哈希表hm中鍵值對的個數(shù)
int size=hm.size();
//定義二維數(shù)組,存放購買物品的信息
String rs[][]=new String[size][];
for(int i=0;i<size;i++)
{
String sid=(String)ii.next(); //存放鍵值對的鍵名,即貨物的編號sid
String[] sa=new String[4];
sa[0]=sid; //獲取購買貨物sid
String[] sat=MongodbBean.getDetail(sid); //根據貨物sid,獲取購買貨物的名稱和價格
sa[1]=sat[0]; //獲取購買貨物名稱
sa[2]=sat[1]; //獲取購買貨物價格
sa[3]=((Integer)hm.get(sid)).toString(); //獲取購買貨物數(shù)量
rs[i]=sa; //將上述單個物品詳細存入二維數(shù)組rs中
}
return rs;
}
}
Buy.jps購物處理腳本代碼如下:
<%@ page language="java" import="java.util.*" contentType="text/html;charset=utf-8" pageEncoding="gb2312"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<jsp:useBean id="cart" scope="session" class="com.liuzhen.shop.ShopCartBean"/>
<%
String action=request.getParameter("action");
if(action==null)
{
%>
<jsp:forward page="main_shop.jsp"/>
<%
}
else if(action.trim().equals("buy"))
{
String sid=request.getParameter("sid");
cart.add(sid.trim());
%>
<jsp:forward page="main_shop.jsp"/>
<%
}
else if(action.trim().equals("gc"))
{
String sid=request.getParameter("sid");
String count=request.getParameter("count");
cart.setCount(Integer.parseInt(count),sid);
%>
<jsp:forward page="Cart.jsp"/>
<%
}
else if(action.trim().equals("del"))
{
String sid=request.getParameter("sid");
cart.deleteFromCart(sid);
%>
<jsp:forward page="Cart.jsp"/>
<%
}
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title></title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
</body>
</html>
2.6.5購物車
購物車功能,主要是用過Cart.jsp頁面調用ShopCartBean.java類來實現(xiàn),ShopCartBean.java類代碼在上面已給出,下面請看Cart.jsp購物車頁面代碼:
<%@ page language="java" import="java.util.*" contentType="text/html;charset=gb2312" import="com.liuzhen.shop.MongodbBean"
pageEncoding="gb2312"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<jsp:useBean id="cart" scope="session" class="com.liuzhen.shop.ShopCartBean"/>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>購物車</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<meta http-equiv="Content-Type" content="text/html;charset=gb2312">
<link rel="stylesheet" type="text/css" href="css/login.css">
</head>
<body>
<div class="content">
<div class="panel1">
<%
if(cart.isEmpty())
{
%>
<font color="red" size="20">購物車中沒有任何商品!??!</Font>
<%
}
else
{
%>
<h2>購物車</h2>
<table border="1">
<tr>
<td width="27%" align="center">物品編號</td>
<td width="27%" align="center">物品名</td>
<td width="27%" align="center">定價</td>
<td width="27%" align="center">數(shù)量</td>
<td width="27%" align="center">求購</td>
</tr>
<%
String[][] ssa=cart.getCart();
for(int i=0;i<ssa.length;i++)
{
%>
<tr>
<td height="30%" align="center"><%= ssa[i][0] %></td>
<td height="30%" align="center"><%= ssa[i][1] %></td>
<td height="30%" align="center"><%= ssa[i][2] %></td>
<td>
<form action="Buy.jsp" method="post">
<input type="text" name="count" value="<%= ssa[i][3] %>">
<input type="hidden" name="sid" value="<%= ssa[i][0] %>">
<input type="hidden" name="action" value="gc">
</form>
</td>
<td><a href="Buy.jsp?sid=<%= ssa[i][0] %>&action=del">刪除</a></td>
</tr>
<%
}
%>
</table>
<br>
<br>
本訂單總價為:<%= Math.round(cart.getTotal()*100)/100.0%>
<%
}
%>
<br>
<div class="register">
<button onclick="window.location.href='main_shop.jsp'">繼續(xù)購物</button>
</div>
</div>
</div>
</body>
</html>
附:源碼下載:源碼
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
jsp中點擊圖片彈出文件上傳界面及實現(xiàn)預覽實例詳解
這篇文章主要介紹了jsp中點擊圖片彈出文件上傳界面及實現(xiàn)預覽實例詳解的相關資料,需要的朋友可以參考下2017-03-03
JSP+Servlet制作Java Web登錄功能的全流程解析
Web頁面登陸功能包括前端的界面以及后臺的數(shù)據庫寫入,這里我們總結了JSP+Servlet制作Java Web登陸功能的全流程解析,需要的朋友可以參考下2016-05-05

