使用MongoDB和JSP實(shí)現(xiàn)一個(gè)簡(jiǎn)單的購物車系統(tǒng)實(shí)例
本文介紹了JSP編程技術(shù)實(shí)現(xiàn)一個(gè)簡(jiǎn)單的購物車程序,具體如下:
1 問題描述
利用JSP編程技術(shù)實(shí)現(xiàn)一個(gè)簡(jiǎn)單的購物車程序,具體要求如下。
(1)用JSP編寫一個(gè)登錄頁面,登錄信息中有用戶名和密碼,分別用兩個(gè)按鈕來提交和重置登錄信息。
(2)編寫一個(gè)JSP程序來獲取用戶提交的登錄信息并查詢數(shù)據(jù)庫,如果用戶名為本小組成員的名字且密碼為對(duì)應(yīng)的學(xué)號(hào)時(shí),采用JSP內(nèi)置對(duì)象的方法跳轉(zhuǎn)到訂購頁面(顯示店中商品的種類和單價(jià)等目錄信息);否則采用JSP動(dòng)作提示用戶重新登錄(注:此頁面上要包含前面的登錄界面)。
(3)當(dāng)顧客填好所需商品的數(shù)量并點(diǎn)擊提交按鈕時(shí),將前面訂購的商品放入購物車中并顯示購物車?yán)锏南嚓P(guān)信息,包括商品的名稱和數(shù)量以及所有商品的總價(jià)格。
(4)將商品信息寫入數(shù)據(jù)庫,計(jì)算價(jià)格時(shí)通過查找數(shù)據(jù)庫來完成。
以下功能選做:
(5) 實(shí)現(xiàn)一個(gè)簡(jiǎn)單的注冊(cè)功能,使新用戶能夠?qū)⒆约旱男畔ⅲㄐ彰蛯W(xué)號(hào))寫進(jìn)數(shù)據(jù)庫,以供后面登錄時(shí)使用
(6)將數(shù)據(jù)庫的相關(guān)操作改寫成一個(gè)JavaBean
2 解決方案
2.1 實(shí)現(xiàn)功能
(1)用戶登錄。(通過查詢MongoDB數(shù)據(jù)庫,完成登錄認(rèn)證)
(2)用戶注冊(cè)。(通過寫入MongoDB數(shù)據(jù)庫,完成用戶注冊(cè))
(3)記住密碼。(通過使用Cookie,實(shí)現(xiàn)記住首頁用戶名和密碼功能)
(4)查看商品。(通過查詢MongoDB數(shù)據(jù)庫,返回商品具體信息,并顯示在客戶端界面)
(5)購買商品。
(6)購物車。(顯示用戶購買商品具體信息,刪除已購買商品或添加已購買商品數(shù)量,計(jì)算用戶當(dāng)前購買商品總價(jià)格)
2.2 最終運(yùn)行效果圖
2.3 系統(tǒng)功能框架示意圖
圖一:系統(tǒng)功能框架示例圖
具體解釋:
(1)瀏覽器中打開首頁login.jsp用戶登錄頁面;
(2)點(diǎn)擊創(chuàng)建新用戶按鈕,進(jìn)入register.jsp用戶注冊(cè)頁面;
(3)注冊(cè)失敗則停留在register.jsp原頁面;注冊(cè)成功則跳轉(zhuǎn)到register_success.jsp注冊(cè)成功提示頁面,點(diǎn)擊返回按鈕,返回到登陸首頁login.jsp頁面;
(4)在首頁login.jsp頁面輸入用戶名和密碼,請(qǐng)求發(fā)送到login_action.jsp登陸處理腳本頁,數(shù)據(jù)匹配成功跳轉(zhuǎn)到welcome.jsp購物首頁頁面,否則跳轉(zhuǎn)到登陸視頻login_Fail.jsp頁面;
(5)進(jìn)入welcome.jsp購物首頁頁面后,點(diǎn)擊下一頁和上一頁按鈕,可以查看當(dāng)前商品信息;同一商品點(diǎn)擊一次購買按鈕實(shí)現(xiàn)購買一件商品,點(diǎn)擊多次則實(shí)現(xiàn)購買多件商品;點(diǎn)擊查看購物車按鈕,實(shí)現(xiàn)內(nèi)部跳轉(zhuǎn)到Cart.jsp購物車頁面,可以產(chǎn)看當(dāng)前購買商品編號(hào)、名稱、價(jià)格、購買數(shù)目以及所有商品總價(jià)格信息,并提供刪除已購買商品和添加已購買商品數(shù)目功能;
(6)購物首頁welcom.jsp頁面由header.jsp、main_shop.jsp、bottom.jsp三個(gè)頁面組成,具體如下圖二所示:
圖二:購物首頁welcome.jsp頁面
2.4 有關(guān)MongoDB簡(jiǎn)介及系統(tǒng)環(huán)境配置
MongoDB是NoSQL家族的一員,和當(dāng)前普遍使用的關(guān)系型數(shù)據(jù)庫(例如,mysql、SQLserver等)相比來說,舍棄了其中復(fù)雜的關(guān)系及實(shí)體間的關(guān)聯(lián)。換句話說,MongoDB是一種文檔型數(shù)據(jù)庫,就和我們?nèi)粘懳臋n一樣,不用去擔(dān)心各類文檔的具體內(nèi)容也不用仔細(xì)分類整理,均可以存放在自己電腦的硬盤里。下面請(qǐng)看一張MongoDB與關(guān)系型數(shù)據(jù)庫名詞概念對(duì)照表:
|
關(guān)系型數(shù)據(jù)庫 |
MongoDB |
|
database(數(shù)據(jù)庫) |
database(數(shù)據(jù)庫) |
|
table(表) |
collection(集合) |
|
row(行) |
document(文檔) |
|
column(列) |
filed(域) |
|
index(索引) |
index(索引) |
|
table joins(表關(guān)系) |
無 |
|
primary key(主鍵) |
自動(dòng)將_id字段設(shè)置為主鍵 |
由上表可知,在我們熟悉的關(guān)系型數(shù)據(jù)庫中,具體的實(shí)體表對(duì)應(yīng)MongoDB中的集合,表中的行對(duì)應(yīng)MongoDB集合中的文檔,表中的列對(duì)應(yīng)MongoDB文檔中的域,最關(guān)鍵的主鍵在MongoDB中是系統(tǒng)自動(dòng)生成,MongoDB自動(dòng)的生成的主鍵是按照特定的方法來生成,具體有12個(gè)字節(jié),12字節(jié)按照如下方式生成:
0|1|2|3 | 4|5|6 | 7|8 | 9|10|11
時(shí)間戳 | 機(jī)器 | PID | 計(jì)數(shù)器
以上是個(gè)人初步學(xué)習(xí)MongoDB的介紹,如有錯(cuò)誤,歡迎各位圓友指正。
說完了概念,就要到具體運(yùn)用,MongoDB中存入和讀取的數(shù)據(jù)格式均為BSON格式,BSON格式是一種類似JSON格式的數(shù)據(jù),其具體樣式如下所示:
/* 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"
},
當(dāng)我們從MongoDB數(shù)據(jù)庫查詢獲取數(shù)據(jù)后,其格式為BSON格式,不能直接與客戶端獲取的數(shù)據(jù)進(jìn)行匹配。在這里,我在獲取數(shù)據(jù)庫中BSON格式數(shù)據(jù)后,調(diào)用MongoDB驅(qū)動(dòng)包中BSON.toMap()方法,把BSON格式轉(zhuǎn)換為Map鍵值對(duì)格式的字符串,然后調(diào)用Map中Map.get(“name”)方法,獲取其中具體鍵值對(duì)的值,從而實(shí)現(xiàn)與客戶端頁面中數(shù)據(jù)的匹配。
最后,最關(guān)鍵的一點(diǎn)就是,在新建項(xiàng)目中導(dǎo)入MongoDB驅(qū)動(dòng)包,方便客戶端和業(yè)務(wù)層操作數(shù)據(jù)庫。這里我使用的是mongo-java-driver-3.3.0.jar包,其各版本驅(qū)動(dòng)包下載鏈接:http://central.maven.org/maven2/org/mongodb/mongo-java-driver/
2.5 核心功能代碼講解
(1)用戶登錄功能
實(shí)現(xiàn)用戶登錄,主要是由login_action.jsp腳本中代碼來實(shí)現(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");//獲取登陸頁面記住密碼選擇框?qū)傩灾?
boolean login_test = false; //設(shè)定登陸布爾值,若用戶名和密碼成功匹配,則為true
try{
// 連接到 mongodb 服務(wù)
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
//此處采用無用戶名和密碼驗(yàn)證方式登陸
@SuppressWarnings("deprecation")
DB db = mongoClient.getDB( "library" ); //連接到數(shù)據(jù)庫library
DBCollection coll = db.getCollection("userInfo"); //獲取library數(shù)據(jù)庫中集合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(); //將檢索結(jié)果show(Bson類型)轉(zhuǎn)換為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ù)據(jù)庫中獲取的用戶名和密碼與表單中獲取的數(shù)據(jù)進(jìn)行驗(yàn)證,匹配成功則使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存取時(shí)用URLEncoder.encode進(jìn)行編碼(PS:讀取時(shí)URLDecoder.decode進(jìn)行解碼)
String name1 = java.net.URLEncoder.encode(userName,"UTF-8");
//創(chuàng)建兩個(gè)Cookie對(duì)象
Cookie nameCookie = new Cookie("username", name1);
//設(shè)置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)用戶注冊(cè)功能
用戶注冊(cè)功能實(shí)現(xiàn)原理基本和用戶登錄一致,唯一的區(qū)別在于用戶登錄是查詢數(shù)據(jù)庫,而用戶注冊(cè)是寫入數(shù)據(jù)庫,此處就不貼具體代碼,在下面具體編碼中展示。
(3)記住密碼功能
實(shí)現(xiàn)記住密碼,此處使用兩個(gè)Cookie,當(dāng)用戶正確登錄時(shí),Cookie_one獲取用戶名,并添加到當(dāng)前瀏覽器Cookie中,Cookie_two獲取密碼,也添加到當(dāng)前瀏覽器Cookie中。在登錄首頁用戶名和密碼兩個(gè)輸入框中的value值填寫系統(tǒng)從Cookie中獲取的用戶名和密碼,從而實(shí)現(xiàn)記住密碼功能。具體如下:
if(login_test) {
if ("save".equals(checkBox)) {
//Cookie存取時(shí)用URLEncoder.encode進(jìn)行編碼(PS:讀取時(shí)URLDecoder.decode進(jìn)行解碼)
String name1 = java.net.URLEncoder.encode(userName,"UTF-8");
//創(chuàng)建兩個(gè)Cookie對(duì)象
Cookie nameCookie = new Cookie("username", name1);
//設(shè)置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 = "";
//獲取當(dāng)前站點(diǎn)的所有Cookie
Cookie[] cookies = request.getCookies();
for (int i = 0; i < cookies.length; i++) {
//對(duì)cookies中的數(shù)據(jù)進(jìn)行遍歷,找到用戶名、密碼的數(shù)據(jù)
if ("username".equals(cookies[i].getName())) {
//讀取時(shí)URLDecoder.decode進(jìn)行解碼(PS:Cookie存取時(shí)用URLEncoder.encode進(jìn)行編碼)
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>簡(jiǎn)單購物車</h1>
</div>
<!-- 登錄面板 -->
<div class="panel">
<form action="login_action.jsp" method="post">
<!-- 賬號(hào)和密碼組 -->
<div class="group">
<label>賬號(hào)</label>
<input type="text" placeholder="請(qǐng)輸入賬號(hào)" name="username" value="<%=username%>">
</div>
<div class="group">
<label>密碼</label>
<input type="password" placeholder="請(qǐng)輸入密碼" 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>
<!-- 注冊(cè)按鈕 -->
<div class="register">
<button onclick="window.location.href='register.jsp'">創(chuàng)建新賬號(hào)</button>
</div>
</div>
</body>
</html>
(4)查詢商品和購買商品
此處功能主要是操作MongoDB數(shù)據(jù)庫,返回商品的具體信息,只要弄懂用戶登錄功能后,此處的功能代碼就會(huì)很快弄明白,具體代碼在后面展示。
(5)購物車
此處的功能也是主要操作MongoDB數(shù)據(jù),通過和客戶端的用戶交互,實(shí)現(xiàn)購物車相關(guān)功能,具體代碼在后面展示。
2.6 具體編碼
具體編碼的講解,就按照實(shí)現(xiàn)功能大致順序來介紹,具體如下:
2.6.1用戶登錄和記住密碼
首先看是登錄首頁login.jsp頁面,為了顯示美觀,此物使用一個(gè)login.css文件(后面多個(gè)頁面均是使用login.css文件)。login.css具體代碼如下:
@CHARSET "UTF-8";
/*按照樣圖要求,添加一個(gè)淺灰色背景*/
body{
background-color: #F2F2F2;
}
/*設(shè)置內(nèi)容模塊距離頂部一個(gè)有一段距離100px*/
.content {
margin-top: 80px;
}
/*登錄和注冊(cè)按鈕的整體樣式*/
.content button {
height: 30px;/*登錄和注冊(cè)按鈕的高度*/
color: white;/*登錄和注冊(cè)按鈕字體顏色為白色*/
font-size: 18px;/*登錄和注冊(cè)按鈕的字體大小*/
border: 0px;/*無邊框*/
padding: 0px;/*無內(nèi)邊距*/
cursor: pointer;/*登錄和注冊(cè)按鈕的選擇時(shí)為手形狀*/
}
/*頭部名稱*/
.content .head {
text-align: center;/*子內(nèi)容居中*/
}
/*登錄面板*/
.content .panel {
background-color: white;/*登錄面板背景顏色為白色*/
width: 302px;/*寬度為302px*/
text-align: center;/*子內(nèi)容居中*/
margin: 0px auto;/*自身居中*/
padding-top: 10px;/*頂部的內(nèi)邊距為20px*/
padding-bottom: 10px;/*底部的內(nèi)邊距為20px*/
border: 1px solid #ddd;/*邊框顏色為灰色*/
border-radius: 5px;/*邊框邊角有5px的弧度*/
}
/*購物主頁購物面板*/
.content .panel1 {
background-color: white;/*購物主頁面板背景顏色為白色*/
width: 1000px;/*寬度為600px*/
text-align: center;/*子內(nèi)容居中*/
margin: 0px auto;/*自身居中*/
border: 1px solid #ddd;/*邊框顏色為灰色*/
border-radius: 5px;/*邊框邊角有5px的弧度*/
}
/*登錄和密碼組*/
.content .panel .group {
text-align: left;/*子內(nèi)容居中*/
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;/*設(shè)置為塊,是為了讓輸入框獨(dú)占一行*/
width: 250px;/*寬度為250px*/
height: 30px;/*高度為30px*/
border: 1px solid #ddd;/*輸入框的邊框*/
padding: 0px 0px 0px 10px;/*左邊內(nèi)邊距為10px,顯得美觀*/
font-size: 16px;/*字體大小*/
}
.content .panel .group input:focus{
border-left: 1px solid #CC865E;/*當(dāng)輸入框成為焦點(diǎn)時(shí),左邊框顏色編程褐色*/
}
.content .panel .login button {
background-color: #CC865E;/*按鈕的背景顏色*/
width: 130px;/*按鈕的寬度*/
}
.content .panel .login button:hover {
background-color: white;/*按鈕選中后背景顏色為白色*/
color: #CC865E;/*按鈕選中后字體顏色為褐色*/
border: 1px solid #CC865E;/*按鈕選中后邊框顏色為褐色*/
}
/*注冊(cè)按鈕*/
.content .register {
text-align: center;/*子內(nèi)容居中*/
margin-top: 20px;/*頂部的內(nèi)邊距為20px*/
}
.content .register button {
background-color: #466BAF;/*按鈕的背景顏色為藍(lán)色*/
width: 180px;/*按鈕的寬度*/
}
.content .register button:hover {
background-color: white;/*按鈕選中后背景顏色為白色*/
color: #466BAF;/*按鈕選中后字體顏色為藍(lán)色*/
border: 1px solid #466BAF;/*按鈕選中后邊框顏色為藍(lán)色*/
}
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 = "";
//獲取當(dāng)前站點(diǎn)的所有Cookie
Cookie[] cookies = request.getCookies();
for (int i = 0; i < cookies.length; i++) {
//對(duì)cookies中的數(shù)據(jù)進(jìn)行遍歷,找到用戶名、密碼的數(shù)據(jù)
if ("username".equals(cookies[i].getName())) {
//讀取時(shí)URLDecoder.decode進(jìn)行解碼(PS:Cookie存取時(shí)用URLEncoder.encode進(jìn)行編碼)
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>簡(jiǎn)單購物車</h1>
</div>
<!-- 登錄面板 -->
<div class="panel">
<form action="login_action.jsp" method="post">
<!-- 賬號(hào)和密碼組 -->
<div class="group">
<label>賬號(hào)</label>
<input type="text" placeholder="請(qǐng)輸入賬號(hào)" name="username" value="<%=username%>">
</div>
<div class="group">
<label>密碼</label>
<input type="password" placeholder="請(qǐng)輸入密碼" 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>
<!-- 注冊(cè)按鈕 -->
<div class="register">
<button onclick="window.location.href='register.jsp'">創(chuàng)建新賬號(hào)</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");//獲取登陸頁面記住密碼選擇框?qū)傩灾?
boolean login_test = false; //設(shè)定登陸布爾值,若用戶名和密碼成功匹配,則為true
try{
// 連接到 mongodb 服務(wù)
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
//此處采用無用戶名和密碼驗(yàn)證方式登陸
@SuppressWarnings("deprecation")
DB db = mongoClient.getDB( "library" ); //連接到數(shù)據(jù)庫library
DBCollection coll = db.getCollection("userInfo"); //獲取library數(shù)據(jù)庫中集合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(); //將檢索結(jié)果show(Bson類型)轉(zhuǎn)換為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ù)據(jù)庫中獲取的用戶名和密碼與表單中獲取的數(shù)據(jù)進(jìn)行驗(yàn)證,匹配成功則使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存取時(shí)用URLEncoder.encode進(jìn)行編碼(PS:讀取時(shí)URLDecoder.decode進(jìn)行解碼)
String name1 = java.net.URLEncoder.encode(userName,"UTF-8");
//創(chuàng)建兩個(gè)Cookie對(duì)象
Cookie nameCookie = new Cookie("username", name1);
//設(shè)置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>輸入用戶名和密碼不正確,請(qǐng)重新登陸?。。?lt;/h1>
</div>
<div class="register">
<button onclick="window.location.href='login.jsp'">返回</button>
</div>
</div>
</body>
</html>
2.6.2用戶注冊(cè)
注冊(cè)首頁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>注冊(cè)頁面</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("兩次密碼輸入不一致,請(qǐng)重新確認(rèn)密碼!??!");
}
</Script>
</head>
<body>
<div class="content">
<div class="head">
<h1>歡迎來到簡(jiǎn)單購物車系統(tǒng)注冊(cè)頁面</h1>
</div>
<!-- 注冊(cè)面板 -->
<div class="panel">
<form name="myform" action="register_action.jsp" method="post">
<!-- 賬號(hào)和密碼組 -->
<div class="group">
<label></label>
<input type="text" placeholder="請(qǐng)輸入注冊(cè)賬號(hào)" name="username1">
</div>
<div class="group">
<label></label>
<input type="password" placeholder="請(qǐng)輸入注冊(cè)密碼" name="password1">
</div>
<div class="group">
<label></label>
<input type="password" placeholder="請(qǐng)確認(rèn)注冊(cè)密碼" name="password2">
</div>
<!-- 注冊(cè)按鈕 -->
<div class="login">
<button type="submit" name="register" onclick="check()">注冊(cè)</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>
注冊(cè)處理腳本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 = "等待注冊(cè)";
%>
<!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");//獲取注冊(cè)頁面密碼1
String passWord2=(String)request.getParameter("password2");//獲取注冊(cè)頁面密碼2
if(!passWord1.equals(passWord2)){
//如果用戶兩次輸入密碼不一致,則跳轉(zhuǎn)到注冊(cè)原頁面register.jsp,即實(shí)現(xiàn)未跳轉(zhuǎn)效果
response.sendRedirect("register.jsp");
}
try{
// 連接到 mongodb 服務(wù)
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
//此處采用無用戶名和密碼驗(yàn)證方式登陸
@SuppressWarnings("deprecation")
DB db = mongoClient.getDB( "library" ); //連接到數(shù)據(jù)庫library
DBCollection coll = db.getCollection("userInfo"); //獲取library數(shù)據(jù)庫中集合userInfo
System.out.println("Collection userInfo selected successfully");
DBObject user = new BasicDBObject();//定義一個(gè)Bson變量,用于存儲(chǔ)注冊(cè)的用戶名和密碼
user.put("username", userName1);
user.put("password", passWord1);
coll.insert(user); //向集合userInfo中插入注冊(cè)用戶信息
response.sendRedirect("register_success.jsp"); //注冊(cè)成功后,自動(dòng)跳轉(zhuǎn)到注冊(cè)成功提示頁面
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
%>
</body>
</html>
成功注冊(cè)提示頁面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>注冊(cè)成功</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>恭喜您,您已經(jīng)成功注冊(cè)簡(jiǎn)單購物車系統(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;">
簡(jiǎn)單購物車系統(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 舞動(dòng)的心</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">物品編號(hào)</th>
<th width="30%" align="center">物品名</th>
<th width="30%" align="center">定價(jià)</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>
實(shí)現(xiàn)查看商品的功能,主要是通過調(diào)用MongodbBean.java類來實(shí)現(xiàn),其具體代碼如下:
package com.liuzhen.shop;
import java.util.Map;
import java.util.Vector;
import com.mongodb.*;
public class MongodbBean {
static int span=5; //設(shè)定JSP頁面表單單頁顯示物品信息行數(shù)為5行
//返回?cái)?shù)據(jù)庫中全部貨物編號(hào)sid
public static String[] getGood_sid(){
String[] good_sid_temporary = new String[100]; //定義一個(gè)長(zhǎng)度為100的暫時(shí)存放貨物編號(hào)的一維數(shù)組
// 連接到 mongodb 服務(wù)
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
//此處采用無用戶名和密碼驗(yàn)證方式登陸
@SuppressWarnings("deprecation")
DB db = mongoClient.getDB( "library" ); //連接到數(shù)據(jù)庫library
DBCollection coll = db.getCollection("good"); //獲取library數(shù)據(jù)庫中集合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(); //將檢索結(jié)果show(Bson類型)轉(zhuǎn)換為Map類型
String tosid = (String)show1.get("sid"); //提取Map中字段名為sid的屬性值
good_sid_temporary[i] = tosid; //將數(shù)據(jù)庫中查詢的貨物編號(hào)存儲(chǔ)入數(shù)組good_sid
i++;
}
String[] good_sid = new String[i]; //根據(jù)查詢數(shù)據(jù)遍歷集合中文檔信息i值來確定最終返回?cái)?shù)組長(zhǎng)度
for(int j=0;j<i;j++){
good_sid[j] = good_sid_temporary[j];
}
return good_sid;
}
//返回?cái)?shù)據(jù)庫中全部貨物名稱sname
public static String[] getGood_sname(){
String[] good_sname_temporary = new String[100]; //定義一個(gè)長(zhǎng)度為100的暫時(shí)存放貨物名稱的一維數(shù)組
// 連接到 mongodb 服務(wù)
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
//此處采用無用戶名和密碼驗(yàn)證方式登陸
@SuppressWarnings("deprecation")
DB db = mongoClient.getDB( "library" ); //連接到數(shù)據(jù)庫library
DBCollection coll = db.getCollection("good"); //獲取library數(shù)據(jù)庫中集合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(); //將檢索結(jié)果show(Bson類型)轉(zhuǎn)換為Map類型
String tosname = (String)show1.get("sname"); //提取Map中字段名為sname的屬性值
good_sname_temporary[i] = tosname; //將數(shù)據(jù)庫中查詢的貨物名稱存儲(chǔ)入數(shù)組good_sname
i++;
}
String[] good_sname = new String[i]; //根據(jù)查詢數(shù)據(jù)遍歷集合中文檔信息i值來確定最終返回?cái)?shù)組長(zhǎng)度
for(int j=0;j<i;j++){
good_sname[j] = good_sname_temporary[j];
}
return good_sname;
}
//返回?cái)?shù)據(jù)庫中全部貨物價(jià)格sprice
public static String[] getGood_sprice(){
String[] good_sprice_temporary = new String[100]; //定義一個(gè)長(zhǎng)度為100的暫時(shí)存放貨物價(jià)格的一維數(shù)組
// 連接到 mongodb 服務(wù)
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
//此處采用無用戶名和密碼驗(yàn)證方式登陸
@SuppressWarnings("deprecation")
DB db = mongoClient.getDB( "library" ); //連接到數(shù)據(jù)庫library
DBCollection coll = db.getCollection("good"); //獲取library數(shù)據(jù)庫中集合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(); //將檢索結(jié)果show(Bson類型)轉(zhuǎn)換為Map類型
String tosprice = (String)show1.get("sprice"); //提取Map中字段名為sname的屬性值
good_sprice_temporary[i] = tosprice; //將數(shù)組庫中查詢的貨物價(jià)格存儲(chǔ)入數(shù)組good_sprice
i++;
}
String[] good_sprice = new String[i]; //根據(jù)查詢數(shù)據(jù)遍歷集合中文檔信息i值來確定最終返回?cái)?shù)組長(zhǎng)度
for(int j=0;j<i;j++){
good_sprice[j] = good_sprice_temporary[j];
}
return good_sprice;
}
//根據(jù)分頁當(dāng)前page數(shù),從數(shù)據(jù)庫中獲取當(dāng)前單個(gè)頁面貨物種類的具體信息,并以二維數(shù)據(jù)返回具體信息
public static String[][] getGoodList(int page)
{
String[][] result=null;
Vector<String[]> v=new Vector<String[]>(); //定義一個(gè)Vector集合,一個(gè)記錄存放一個(gè)貨物的具體信息
String[] good_sid = getGood_sid(); //獲取貨物編號(hào)
String[] good_sname = getGood_sname(); //獲取貨物名稱
String[] good_sprice = getGood_sprice(); //獲取貨物價(jià)格
int len = good_sid.length;
for(int i=0;i<span;i++){
int t = (page-1)*span+i; //獲取貨物編號(hào)
if(t >= len){
//如果當(dāng)前貨物編號(hào)大于數(shù)據(jù)庫中已有編號(hào),則跳出循環(huán)
break;
}
String[] good_temp=new String[3]; //定義一個(gè)長(zhǎng)度為3的數(shù)組,用于存放一個(gè)物品的編號(hào)、名稱、價(jià)格信息
good_temp[0]=good_sid[t];
good_temp[1]=good_sname[t];
good_temp[2]=good_sprice[t];
v.add(good_temp); //將1個(gè)物品的信息存入Vector集合中
}
int size = v.size();
result=new String[size][]; //根據(jù)Vercotr大小,給result指定行數(shù)大小
for(int j=0;j<size;j++)
{
//返回Vector中一個(gè)值(其中即表示一個(gè)物品的sid,名稱和價(jià)格),并賦值給result[j],即result二維數(shù)組一行表示一個(gè)物品具體信息
result[j]=(String[])v.elementAt(j);
}
return result;
}
//根據(jù)貨物sid,返回其價(jià)格信息
public static double getPrice(String sid)
{
double price = 0; //定義返回物品的價(jià)格
String[] good_sprice = getGood_sprice(); //獲取全部物品的價(jià)格
int i = Integer.parseInt(sid); //將String類型的物品編號(hào)sid轉(zhuǎn)換為int型
String sprice = good_sprice[i]; //根據(jù)sid獲取物品的價(jià)格
price = Double.parseDouble(sprice); //將String類型的價(jià)格信息轉(zhuǎn)換為double型,并賦值給price
return price;
}
//根據(jù)貨物sid,返回貨物的名稱和價(jià)格,一一個(gè)長(zhǎng)度為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(); //獲取全部物品價(jià)格
int i = Integer.parseInt(sid); //將String類型的物品編號(hào)sid轉(zhuǎn)換為int型
good_detail[0] = good_sname[i]; //根據(jù)物品編號(hào)sid,得到名稱存入數(shù)組good_detail中
good_detail[1] = good_sprice[i]; //根據(jù)物品編號(hào)sid,得到物品價(jià)格存入數(shù)組good_detail中
return good_detail;
}
//通過查詢數(shù)據(jù)庫中貨物種類數(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)行為一頁,計(jì)算貨物具有的頁數(shù)page
return page;
}
//返回一個(gè)二維數(shù)組的行數(shù)大小
public static int getlength(String[][] a){
return a.length;
}
public static void main(String args[]){
// String[] good_sid = getGood_sid(); //定義一個(gè)存放貨物編號(hào)的一維數(shù)組
// String[] good_sname = getGood_sname(); //定義一個(gè)存放貨物名稱的一維數(shù)組
// String[] good_sprice = getGood_sprice(); //定義一個(gè)存放貨物價(jià)格的一維數(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ù)目(測(cè)試):"+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ù)組長(zhǎng)度為:"+n);
}
}
2.6.4購買商品
實(shí)現(xiàn)購買商品,通過Buy.jsp業(yè)務(wù)處理腳本調(diào)用ShopCartBean.java類來實(shí)現(xiàn)。
ShopCartBean.java類代碼如下:
package com.liuzhen.shop;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
public class ShopCartBean {
//ShopCartBean類構(gòu)造函數(shù)
public ShopCartBean(){
}
//定義一個(gè)存儲(chǔ)整形數(shù)值的鍵值對(duì)hashMap
HashMap<String, Integer> hm=new HashMap<String, Integer>();
//定義購物車總物品總價(jià)格,初始值為0
double total=0;
//添加購買的物品,存入哈希表hm中,并計(jì)算購買成功后的總價(jià)格
public void add(String sid)
{
if(hm.containsKey(sid))
{
//如果hm中包含鍵值對(duì)sid,則獲取該鍵值對(duì)中的值,并加1
int xc=((Integer)hm.get(sid)).intValue()+1;
//把上面獲取的xc值存入hm中
hm.put(sid,new Integer(xc));;
}
else
{
//如果hm中不包含鍵值對(duì)sid,則將該鍵值對(duì)存入hm中,并該鍵值對(duì)值為1
hm.put(sid,new Integer(1));
}
total=total+MongodbBean.getPrice(sid); //購買物品后,計(jì)算物品總價(jià)格
}
//獲取購物車當(dāng)前物品總價(jià)格
public double getTotal()
{
return total;
}
//根據(jù)物品編號(hào)sid,設(shè)定購買物品數(shù)目,并將購買數(shù)目存入哈希表hm中,并更新當(dāng)前購物車物品總價(jià)格
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));
}
//根據(jù)物品編號(hào)sid,從購物車中刪除物品,并刪除存入哈希表hm中物品的數(shù)目,以及當(dāng)前購物車物品總價(jià)格
public void deleteFromCart(String sid)
{
int yc=((Integer)hm.get(sid)).intValue();
total=total-yc*MongodbBean.getPrice(sid);
hm.remove(sid);
}
//判斷當(dāng)前哈希表hm是否為空
public boolean isEmpty()
{
return hm.isEmpty();
}
//返回用戶購買物品的詳細(xì)信息(物品編號(hào)、物品名稱、物品價(jià)格、物品購買數(shù)量)
public String[][] getCart()
{
//定義一個(gè)set集合,存放哈希表hm中鍵值對(duì)的鍵名稱
Set<String> ks=hm.keySet();
//定義一個(gè)迭代器,用于遍歷set集合
Iterator<String> ii=ks.iterator();
//獲取哈希表hm中鍵值對(duì)的個(gè)數(shù)
int size=hm.size();
//定義二維數(shù)組,存放購買物品的信息
String rs[][]=new String[size][];
for(int i=0;i<size;i++)
{
String sid=(String)ii.next(); //存放鍵值對(duì)的鍵名,即貨物的編號(hào)sid
String[] sa=new String[4];
sa[0]=sid; //獲取購買貨物sid
String[] sat=MongodbBean.getDetail(sid); //根據(jù)貨物sid,獲取購買貨物的名稱和價(jià)格
sa[1]=sat[0]; //獲取購買貨物名稱
sa[2]=sat[1]; //獲取購買貨物價(jià)格
sa[3]=((Integer)hm.get(sid)).toString(); //獲取購買貨物數(shù)量
rs[i]=sa; //將上述單個(gè)物品詳細(xì)存入二維數(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頁面調(diào)用ShopCartBean.java類來實(shí)現(xiàn),ShopCartBean.java類代碼在上面已給出,下面請(qǐng)看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">物品編號(hào)</td>
<td width="27%" align="center">物品名</td>
<td width="27%" align="center">定價(jià)</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>
本訂單總價(jià)為:<%= 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>
附:源碼下載:源碼
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
jsp輸出當(dāng)前時(shí)間的實(shí)現(xiàn)代碼
下面小編就為大家?guī)硪黄猨sp輸出當(dāng)前時(shí)間的實(shí)現(xiàn)代碼。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-06-06
jsp中點(diǎn)擊圖片彈出文件上傳界面及實(shí)現(xiàn)預(yù)覽實(shí)例詳解
這篇文章主要介紹了jsp中點(diǎn)擊圖片彈出文件上傳界面及實(shí)現(xiàn)預(yù)覽實(shí)例詳解的相關(guān)資料,需要的朋友可以參考下2017-03-03
JSP+Servlet制作Java Web登錄功能的全流程解析
Web頁面登陸功能包括前端的界面以及后臺(tái)的數(shù)據(jù)庫寫入,這里我們總結(jié)了JSP+Servlet制作Java Web登陸功能的全流程解析,需要的朋友可以參考下2016-05-05

