PHP完毕三个简陋的注册登录页面,使用MongoDB和JSP达成八个大致的购物车系统

PHP完结五个简陋的登记登录页面

后天来水一篇没有**用的
/滑稽脸,代码简陋臃肿考虑不全,各位大佬轻喷,还望不吝赐教。
先是考虑了一晃须要至少八个页面:register.htmlregister.phplogin.htmllogin.php
register.html是如此写的:

<!DOCTYPE html>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<head>
    <title>注册界面</title>
</head>
<body>
    <form action="register.php" method="post">
        用户名:<input type="text" name="name"></input>
        <br />
        密码:<input type="password" name="password"></input>
        <br />
        <input type="submit" value="注册"></input>
    </form>
</body>
</html>

register.php是那样写的:

<?php
    header("Content-type:text/html;charset=utf-8");
    $conn=new mysqli('localhost','wy','000000','test');
    if ($conn->connect_error){
        die("服务器连接失败!");
    }
    $name=$_POST["name"];
    $password=$_POST["password"];
    $sql="insert into new_info values('$name',$password)";
    $res=$conn->query($sql);
    if(!$res){
        echo "注册失败!";
    }else{
            if($conn->affected_rows>0){
                sleep(2);
                header("Location:login.html");
                exit;
            }else{
                echo "注册失败";
            }
    }
    $conn->close();
?>

login.html是这么写的:

<!DOCTYPE html>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<head>
    <title>登录界面</title>
</head>
<body>
    <p>注册成功,请登录!</p>
    <form action="login.php" method="post">
        用户名:<input type="text" name="name"></input>
        <br />
        密码:<input type="password" name="password"></input>
        <br />
        <input type="submit" value="登录"></input>
    </form>
</body>
</html>

login.php是那般写的:

<?php
    header("Content-type:text/html;charset=utf-8");
    $conn=new mysqli('localhost','wy','000000','test');
    if ($conn->connect_error){
        die("服务器连接失败!");
    }
    $name=$_POST["name"];
    $password=$_POST["password"];
    $sql_name="select name from new_info where name='$name'";
    $res_sql=$conn->query($sql_name);
    if($conn->affected_rows==0){
        die("账号或密码有误");
    }else{
        $sql_pass="select password from new_info where name='$name'";
        $res_pass=$conn->query($sql_pass);
        $row_pass=$res_pass->fetch_row();
        if($row_pass[0]==$password){
            echo "登录成功!";
        }else{
            echo "账号或密码有误";
        }
    }
    $conn->close();
?>

接下来来看一下功用:
亚洲必赢官网 1
亚洲必赢官网 2

看一下数据库:
亚洲必赢官网 3

能够看来曾经将数据写入数据库。
继之来登录试一下:
亚洲必赢官网 4
亚洲必赢官网 5

换个谬误密码试一下:
亚洲必赢官网 6
亚洲必赢官网 7

2018-09-04 难点订正:

1.用户密码加密

register.php页面:

<?php
    header("Content-type:text/html;charset=utf-8");
    $conn=new mysqli('192.168.134.128','root','123456','test');
    if ($conn->connect_error){
        die("服务器连接失败!");
    }
    $name=$_POST["name"];
    $password=$_POST["password"];
    $password=md5($password);     //将用户输入的密码进行md5加密
    $sql="insert into test values('$name','$password')";
    $res=$conn->query($sql);
    if(!$res){
        echo "注册失败!";
   }else{
            if($conn->affected_rows>0){
                sleep(2);
                header("Location:login.html");
            }else{
                echo "注册失败";
            }
    }
    $conn->close();
?>

login.php页面:

<?php
    header("Content-type:text/html;charset=utf-8");
    $conn=new mysqli('192.168.134.128','root','123456','test');
    if ($conn->connect_error){
        die("服务器连接失败!");
    }
    $name=$_POST["name"];
    $password=$_POST["password"];
    $password=md5($password);    //对用户输入的密码进行md5加密
    $sql_name="select name from test where name='$name'";
    $res_sql=$conn->query($sql_name);
    if($conn->affected_rows==0){
        die("账号或密码有误!");
    }else{
        $sql_pass="select password from test where name='$name'";
        $res_pass=$conn->query($sql_pass);
        $row_pass=$res_pass->fetch_row();
        if($row_pass[0]==$password){            //将用户输入的加密密码与数据库密码进行对比
            echo "登录成功!";
        }else{
            echo "账号或密码有误";
        }
    }
    $conn->close();
?>

2.数据库编码难点
在数据库执行set names utf8一声令下,将数据库编码改为utf8
诸如此类就可以利用中文名注册登录。

目录

1 style=”font-family: 金鼎文;”>难点讲述 

2 style=”font-family: 甲骨文;”>消除方案 

2.1   style=”font-family: 金鼎文;”>完毕效益 

2.2   style=”font-family: 小篆;”>最终运营效果图 

2.3   style=”font-family: 仿宋;”>系统作用框架示意图 

2.4   style=”font-family: 草书;”>有关 style=”font-family: Calibri;”>MongoDB style=”font-family: 陶文;”>简介及系统环境安插 

2.5   style=”font-family: 钟鼓文;”>焦点功用代码讲解PHP完毕三个简陋的注册登录页面,使用MongoDB和JSP达成八个大致的购物车系统。 

2.6   style=”font-family: 燕书;”>具体编码 

2.6.1 style=”font-family: 大篆;”>用户登录和铭记密码 

2.6.2 style=”font-family: 钟鼓文;”>用户注册 

2.6.3 style=”font-family: 燕体;”>查看商品 

2.6.4 style=”font-family: 钟鼓文;”>购买商品 

2.6.5 style=”font-family: 宋体;”>购物车 

行使MongoDB和JSP完成3个大致的购物车系统,mongodb购物车

目录
1 问题描述 
2 解决方案 
2.1  实现功能 
2.2  最终运行效果图 
2.3  系统功能框架示意图 
2.4  有关MongoDB简介及系统环境配置 
2.5  核心功能代码讲解 
2.6  具体编码 
2.6.1用户登录和记住密码 
2.6.2用户注册 
2.6.3查看商品 
2.6.4购买商品 
2.6.5购物车 

实验二   JSP编程

 

 


一.实验指标1. 控制JSP**指令的利用办法;2. 左右JSP**动作的施用方法;3. 操纵JSP**放到对象的使用办法;4. 控制JavaBean的编制程序技术及使用方法;5. 精通JSP中数据库编制程序**方法;

 

1 难题讲述

使用JSP编制程序技术完结二个总结的购物车程序,具体需要如下。

(1)用JSP编写1个报到页面,登录音讯中有用户名和密码,分别用八个按钮来交付和重置登录音信。

(2)编写贰个JSP程序来博取用户提交的记名音讯并查询数据库,借使用户名为本小组成员的名字且密码为对应的学号时,接纳JSP内置对象的法子跳转到订购页面(显示店中货物的档次和单价等目录音信);不然采取JSP动作提示用户重新登录(注:此页面上要包罗前边的登录界面)。

(3)当顾客填好所需商品的多寡并点击提交按钮时,将前方订购的货物放入购物车中并出示购物车里的相关消息,包括商品的名称和数目以及具有商品的总价格。

(4)将商品音讯写入数据库,计算价格时通过寻找数据库来达成。

以下功效选做

(5)
达成一个大约的登记功能,使新用户能够将团结的音讯(姓名和学号)写进数据库,以供前边登录时使用

(6)将数据库的连锁操作改写成3个JavaBean

 

 


 二.试行须求 : 利用JSP编制程序技术完结多个简练的购物车程序,具体须求如下。


2 解决方案

(1)用JSP编写二个报到页面,登录音信中有用户名和密码,分别用两个按钮来交付和重置登录音信。

1 难点讲述

利用JSP编制程序技术达成贰个简易的购物车程序,具体供给如下。

(1)用JSP编写二个登录页面,登录信息中有用户名和密码,分别用八个按钮来交给和重置登录音讯。

(2)编写一个JSP程序来获得用户提交的登录新闻并查询数据库,假如用户名为本小组成员的名字且密码为相应的学号时,选取JSP内置对象的办法跳转到订购页面(显示店中货物的类型和单价等目录音讯);不然采取JSP动作提醒用户重新登录(注:此页面上要蕴含前边的登录界面)。

(3)当顾客填好所需商品的数目并点击提交按钮时,将日前订购的货色放入购物车中并显示购物车里的相干音信,包罗商品的称谓和数码以及具有商品的总价格。

(4)将商品消息写入数据库,总计价格时通过搜索数据库来形成。

以下职能选做

(5)
实现3个简短的注册效用,使新用户能够将自个儿的消息(姓名和学号)写进数据库,以供前面登录时使用

(6)将数据库的连带操作改写成二个JavaBean

 

 


2.1  达成效益

(1)用户登录。(通过询问MongoDB数据库,达成报到认证)

(2)用户注册。(通过写入MongoDB数据库,完成用户注册)

(3)记住密码。(通过运用Cookie,完结记住首页用户名和密码成效)

(4)查看商品。(通过询问MongoDB数据库,重临商品实际音信,并体以后客户端界面)

(5)购买商品。

(6)购物车。(展现用户购买商品实际新闻,删除已购买商品或加上已购置商品数量,总结用户近期买入商品总价格)

(2)编写一个JSP程序来处理用户提交的报到音讯,假使用户名为本小组成员的名字且密码为对应的学号时,选择JSP内置对象的方式跳转到订购页面(展现店中货物的类型和单价等目录音讯);不然采取JSP动作提示用户重新登录(注:此页面上要包罗后面包车型客车报到界面)

2 消除方案

2.2  最后运维效果图

 

(3)当消费者填好所需商品的数据并点击提交按钮时,将日前订购的货物放入购物车中并出示购物车里的相干音信,包含商品的名目和多少以及有着商品的总价格(关于总价格的持筹握算,供给通过编写制定贰个JavaBean来援救完毕)。

2.1  完结效益

(1)用户登录。(通过询问MongoDB数据库,达成报到认证)

(2)用户注册。(通过写入MongoDB数据库,完结用户注册)

(3)记住密码。(通过应用Cookie,完结记住首页用户名和密码功效)

(4)查看商品。(通过查询MongoDB数据库,再次回到商品实际消息,并出示在客户端界面)

(5)购买商品。

(6)购物车。(显示用户购买商品实际新闻,删除已买卖商品或添加已购进商品数量,统计用户日前购买商品总价格)

2.3  系统作用框架示意图

 

 

图一:系统成效框架示例图

现实解释:

(1)浏览器中开拓首页login.jsp用户登录页面;

(2)点击创设新用户按钮,进入register.jsp用户注册页面;

(3)注册战败则停留在register.jsp原页面;注册成功则跳转到register_success.jsp注册成功唤醒页面,点击再次回到按钮,再次回到到登陆首页login.jsp页面;

(4)在首页login.jsp页面输入用户名和密码,请求发送到login_action.jsp登陆处理脚本页,数据匹配成功跳转到welcome.jsp购物首页页面,不然跳转到登陆摄像login_Fail.jsp页面;

(5)进入welcome.jsp购物首页页面后,点击下一页和上一页按钮,能够查看当前商品消息;同一商品点击一回购买按钮完毕购销一件货物,点击数次则贯彻购销多件商品;点击查阅购物车按钮,实现内部跳转到Cart.jsp购物车页面,能够产看当前进货商品编号、名称、价格、购买数码以及拥有商品总价格新闻,并提供删除已购置商品和增加已购进商品数量效能;

(6)购物首页welcom.jsp页面由header.jsp、main_shop.jsp、bottom.jsp两个页面组成,具体如下图二所示:

 

图二:购物首页welcome.jsp页面

 

(4)修改登录程序。将法定用户新闻(用户名)写入数据库中,登录时经过搜索数据库来成功报到。 

2.2  最终运营效果图

 亚洲必赢官网 8

2.4  有关MongoDB简介及系统环境布置

    
MongoDB是NoSQL家族的一员,和如今普遍应用的关系型数据库(例如,mysql、SQLserver等)相比较来说,放任了中间复杂的关系及实体间的涉嫌。换句话说,MongoDB是一种文书档案型数据库,就和我们平时写文书档案一样,不用去担心各样文书档案的具体内容也不用仔细分类整理,均可以存放在融洽电脑的硬盘里。上边请看一张MongoDB与关系型数据库名词概念对照表:

关系型数据库

MongoDB

database(数据库)

database(数据库)

table(表)

collection(集合)

row(行)

document(文档)

column(列)

filed(域)

index(索引)

index(索引)

table joins(表关系)

primary key(主键)

自动将_id字段设置为主键

 

   
 由上表可见,在大家熟悉的关系型数据库中,具体的实身体表面对应MongoDB中的集合,表中的行对应MongoDB集合中的文书档案,表中的列对应MongoDB文书档案中的域,最关键的主键在MongoDB中是系统自动生成,MongoDB自动的生成的主键是比照一定的方法来扭转,具体有13个字节,12字节遵照如下格局生成: 
      0|1|2|3 | 4|5|6 | 7|8 | 9|10|11 
        时间戳 | 机器  | PID | 计数器 

    以上是个体开头学习MongoDB的介绍,如有错误,欢迎各位圆友指正。

 
 说完了定义,就要到具体行使,MongoDB中存入和读取的多少格式均为BSON格式,BSON格式是一连串似JSON格式的多寡,其现实样式如下所示:

/* 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数据库查询获取数据后,其格式为BSON格式,不能够直接与客户端获取的数量开始展览匹配。在那边,作者在收获数据库中BSON格式数据后,调用MongoDB驱动包中BSON.toMap()方法,把BSON格式转换为Map键值对格式的字符串,然后调用Map中Map.get(“name”)方法,获取在那之中具体键值对的值,从而完结与客户端页面中多少的合营。

   最终,最关键的一些正是,在新建项目中程导弹入MongoDB驱动包,方便客户端和业务层操作数据库。那里本人使用的是mongo-java-driver-3.3.0.jar包,其各版本驱动包下载链接:

,github源码链接:

 

(5)将商品音信写入数据库,总括价格时经过查找数据库来成功。

2.3  系统效率框架示意图

 亚洲必赢官网 9

 

图一:系统效率框架示例图

切实表明:

(1)浏览器中开拓首页login.jsp用户登录页面;

(2)点击成立新用户按钮,进入register.jsp用户注册页面;

(3)注册战败则停留在register.jsp原页面;注册成功则跳转到register_success.jsp注册成功唤醒页面,点击再次回到按钮,再次回到到登陆首页login.jsp页面;

(4)在首页login.jsp页面输入用户名和密码,请求发送到login_action.jsp登陆处理脚本页,数据匹配成功跳转到welcome.jsp购物首页页面,不然跳转到登陆录像login_Fail.jsp页面;

(5)进入welcome.jsp购物首页页面后,点击下一页和上一页按钮,能够查看当前商品音信;同一商品点击壹遍购买按钮达成购买一件商品,点击多次则贯彻购销多件货物;点击查阅购物车按钮,实现内部跳转到Cart.jsp购物车页面,能够产看当前选购商品编号、名称、价格、购买数量以及具有商品总价格消息,并提供删除已购置商品和丰硕已购置商品数量功效;

(6)购物首页welcom.jsp页面由header.jsp、main_shop.jsp、bottom.jsp多个页面组成,具体如下图二所示:

 亚洲必赢官网 10

图二:购物首页welcome.jsp页面

 

2.5  大旨功效代码讲解

(1)用户登录作用

     达成用户登录,首假如由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" );  //连接到数据库library
            DBCollection coll = db.getCollection("userInfo");  //获取library数据库中集合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)){  
                //将从数据库中获取的用户名和密码与表单中获取的数据进行验证,匹配成功则使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");
                //创建两个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)用户注册功效

用户注册成效完成原理基本和用户登录一致,唯一的区分在于用户登录是查询数据库,而用户注册是写入数据库,此处就不贴具体代码,在上面具体编码中显得。

 (3)记住密码作用

落到实处记住密码,此处使用多个Cookie,当用户不利登录时,Cookie_one得到用户名,并添加到当前浏览器Cookie中,Cookie_two获取密码,也丰富到眼下浏览器Cookie中。在报到首页用户名和密码四个输入框中的value值填写系统从Cookie中获取的用户名和密码,从而达成记住密码作用。具体如下:

 if(login_test) {
            if ("save".equals(checkBox)) {
                //Cookie存取时用URLEncoder.encode进行编码(PS:读取时URLDecoder.decode进行解码)
                String name1 = java.net.URLEncoder.encode(userName,"UTF-8");
                //创建两个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中的数据进行遍历,找到用户名、密码的数据
         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'">创建新账号</button>
        </div>

    </div>
  </body>
</html>

 (4)查询商品和购买商品

此间功效首假使操作MongoDB数据库,重返商品的求实新闻,只要弄懂用户登录功效后,此处的成效代码就会急迅弄理解,具体代码在后头展示。

 (5)购物车

    此处的效果也是人命关天操作MongoDB数据,通过和客户端的用户交互,达成购物车相关职能,具体代码在末端体现。

亚洲必赢官网, 

 

2.4  有关MongoDB简介及系统环境安排

     MongoDB是NoSQL家族的一员,和脚下广泛选用的关系型数据库(例如,mysql、SQLserver等)相比较来说,吐弃了内部复杂的涉嫌及实体间的涉及。换句话说,MongoDB是一种文书档案型数据库,就和大家日常写文书档案一样,不用去担心各样文书档案的具体内容也不用仔细分类整理,均能够存放在团结电脑的硬盘里。上面请看一张MongoDB与关系型数据库名词概念对照表:

关系型数据库

MongoDB

database(数据库)

database(数据库)

table(表)

collection(集合)

row(行)

document(文档)

column(列)

filed(域)

index(索引)

index(索引)

table joins(表关系)

primary key(主键)

自动将_id字段设置为主键

 

     由上表可见,在大家明白的关系型数据库中,具体的实体表对应MongoDB中的集合,表中的行对应MongoDB集合中的文书档案,表中的列对应MongoDB文档中的域,最要害的主键在MongoDB中是系统自动生成,MongoDB自动的成形的主键是依据一定的办法来变化,具体有10个字节,12字节依据如下方式生成: 
     
0|1|2|3 | 4|5|6 | 7|8 | 9|10|11 
        时间戳 | 机器  | PID | 计数器 

    以上是私家早先学习MongoDB的介绍,如有错误,欢迎各位圆友指正。

   说完了概念,就要到实际行使,MongoDB中存入和读取的数额格式均为BSON格式,BSON格式是一种恍若JSON格式的多少,其现实样式如下所示:

/* 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数据库查询获取数据后,其格式为BSON格式,不能够一贯与客户端获取的数据实行匹配。在那里,我在赢得数据库中BSON格式数据后,调用MongoDB驱动包中BSON.toMap()方法,把BSON格式转换为Map键值对格式的字符串,然后调用Map中Map.get(“name”)方法,获取在那之中实际键值对的值,从而完成与客户端页面中数据的杰出。

   最终,最根本的一点就是,在新建项目中导入MongoDB驱动包,方便客户端和业务层操作数据库。那里作者使用的是mongo-java-driver-3.3.0.jar包,其各版本驱动包下载链接:

,github源码链接:

 

2.6  具体编码

切实编码的讲解,就遵照贯彻效益大概顺序来介绍,具体如下:

 

2.5  核心作用代码讲解

(1)用户登录作用

     达成用户登录,首倘使由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" );  //连接到数据库library
            DBCollection coll = db.getCollection("userInfo");  //获取library数据库中集合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)){  
                //将从数据库中获取的用户名和密码与表单中获取的数据进行验证,匹配成功则使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");
                //创建两个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)用户注册功用

用户注册功效完成原理基本和用户登录一致,唯一的界别在于用户登录是查询数据库,而用户注册是写入数据库,此处就不贴具体代码,在底下具体编码中展现。

 (3)记住密码功效

落实记住密码,此处使用多个Cookie,当用户不利登录时,Cookie_one获得用户名,并添加到当前浏览器Cookie中,Cookie_two获取密码,也添加到当下浏览器库克ie中。在登录首页用户名和密码三个输入框中的value值填写系统从Cookie中获得的用户名和密码,从而达成记住密码作用。具体如下:

 if(login_test) {
            if ("save".equals(checkBox)) {
                //Cookie存取时用URLEncoder.encode进行编码(PS:读取时URLDecoder.decode进行解码)
                String name1 = java.net.URLEncoder.encode(userName,"UTF-8");
                //创建两个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中的数据进行遍历,找到用户名、密码的数据
         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'">创建新账号</button>
        </div>

    </div>
  </body>
</html>

 (4)查询商品和进货商品

此地成效首借使操作MongoDB数据库,再次回到商品的切切实实音讯,只要弄懂用户登录作用后,此处的功力代码就会火速弄掌握,具体代码在前边呈现。

 (5)购物车

    此处的效益也是必不可缺操作MongoDB数据,通过和客户端的用户交互,达成购物车相关职能,具体代码在后头彰显。

 

2.6.1用户登录和记住密码

率先看是登录首页login.jsp页面,为了展现赏心悦目,此物使用2个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中的数据进行遍历,找到用户名、密码的数据
         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'">创建新账号</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" );  //连接到数据库library
            DBCollection coll = db.getCollection("userInfo");  //获取library数据库中集合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)){  
                //将从数据库中获取的用户名和密码与表单中获取的数据进行验证,匹配成功则使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");
                //创建两个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页面代码如下:

亚洲必赢官网 11

<%@ 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>

View Code

 

 

2.6  具体编码

切切实实编码的任课,就遵照贯彻效益大概顺序来介绍,具体如下:

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>欢迎来到简单购物车系统注册页面</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,即实现未跳转效果
               response.sendRedirect("register.jsp"); 
         }

         try{   
             // 连接到 mongodb 服务
             MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
             //此处采用无用户名和密码验证方式登陆
             @SuppressWarnings("deprecation")
             DB db = mongoClient.getDB( "library" );  //连接到数据库library
             DBCollection coll = db.getCollection("userInfo");  //获取library数据库中集合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页面代码如下:

亚洲必赢官网 12

<%@ 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>

View Code

 

在jsp中用include指令引入html文件时遇见的标题:

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中的数据进行遍历,找到用户名、密码的数据
         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'">创建新账号</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" );  //连接到数据库library
            DBCollection coll = db.getCollection("userInfo");  //获取library数据库中集合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)){  
                //将从数据库中获取的用户名和密码与表单中获取的数据进行验证,匹配成功则使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");
                //创建两个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页面代码如下:

亚洲必赢官网 13亚洲必赢官网 14

<%@ 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>

View Code

 

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页面代码:

亚洲必赢官网 15

<%@ 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;">
                     简单购物车系统
                   </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>

View Code

底部bottom.jsp页面代码:

亚洲必赢官网 16

<%@ 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>

View Code

首页中间主体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为分页数
//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>

 

贯彻底追查看商品的效用,主借使经过调用MongodbBean.java类来促成,其切实代码如下:

package com.liuzhen.shop;

import java.util.Map;
import java.util.Vector;

import com.mongodb.*;

public class MongodbBean {

    static int span=5;    //设定JSP页面表单单页显示物品信息行数为5行

    //返回数据库中全部货物编号sid
    public static String[] getGood_sid(){
        String[] good_sid_temporary = new String[100];    //定义一个长度为100的暂时存放货物编号的一维数组    
         // 连接到 mongodb 服务
        MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
        //此处采用无用户名和密码验证方式登陆
        @SuppressWarnings("deprecation")
        DB db = mongoClient.getDB( "library" );  //连接到数据库library
        DBCollection coll = db.getCollection("good");  //获取library数据库中集合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;         //将数据库中查询的货物编号存储入数组good_sid                              
           i++;
         }
        String[] good_sid = new String[i];   //根据查询数据遍历集合中文档信息i值来确定最终返回数组长度
        for(int j=0;j<i;j++){
            good_sid[j] = good_sid_temporary[j];
        }

        return good_sid;
    }

    //返回数据库中全部货物名称sname
    public static String[] getGood_sname(){
        String[] good_sname_temporary = new String[100];  //定义一个长度为100的暂时存放货物名称的一维数组
         // 连接到 mongodb 服务
        MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
        //此处采用无用户名和密码验证方式登陆
        @SuppressWarnings("deprecation")
        DB db = mongoClient.getDB( "library" );  //连接到数据库library
        DBCollection coll = db.getCollection("good");  //获取library数据库中集合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;     //将数据库中查询的货物名称存储入数组good_sname                         
           i++;
        }
        String[] good_sname = new String[i];   //根据查询数据遍历集合中文档信息i值来确定最终返回数组长度
        for(int j=0;j<i;j++){
            good_sname[j] = good_sname_temporary[j];
        }
        return good_sname;
    }

    //返回数据库中全部货物价格sprice
    public static String[] getGood_sprice(){
        String[] good_sprice_temporary = new String[100]; //定义一个长度为100的暂时存放货物价格的一维数组
         // 连接到 mongodb 服务
        MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
        //此处采用无用户名和密码验证方式登陆
        @SuppressWarnings("deprecation")
        DB db = mongoClient.getDB( "library" );  //连接到数据库library
        DBCollection coll = db.getCollection("good");  //获取library数据库中集合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;   //将数组库中查询的货物价格存储入数组good_sprice                     
           i++;
        }
        String[] good_sprice = new String[i];   //根据查询数据遍历集合中文档信息i值来确定最终返回数组长度
        for(int j=0;j<i;j++){
            good_sprice[j] = good_sprice_temporary[j];
        }
        return good_sprice;
    }

    //根据分页当前page数,从数据库中获取当前单个页面货物种类的具体信息,并以二维数据返回具体信息
    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= len){ 
                //如果当前货物编号大于数据库中已有编号,则跳出循环
                break;
            }

            String[] good_temp=new String[3];   //定义一个长度为3的数组,用于存放一个物品的编号、名称、价格信息
            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指定行数大小
        for(int j=0;j<size;j++)
        {
           //返回Vector中一个值(其中即表示一个物品的sid,名称和价格),并赋值给result[j],即result二维数组一行表示一个物品具体信息
            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的数组返回
    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,得到名称存入数组good_detail中
        good_detail[1] = good_sprice[i];       //根据物品编号sid,得到物品价格存入数组good_detail中        

        return good_detail;
    }

    //通过查询数据库中货物种类数目,以5行为一页,返回现有货物页数
    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)行为一页,计算货物具有的页数page

        return page;            
    }



    //返回一个二维数组的行数大小
    public static int getlength(String[][] a){
        return a.length;
    }


    public static void main(String args[]){
//        String[] good_sid = getGood_sid();    //定义一个存放货物编号的一维数组
//        String[] good_sname = getGood_sname();  //定义一个存放货物名称的一维数组
//        String[] good_sprice = getGood_sprice(); //定义一个存放货物价格的一维数组
//                                      
//        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("分页数目(测试):"+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("数组长度为:"+n);


    }


}

 

 

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>欢迎来到简单购物车系统注册页面</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,即实现未跳转效果
               response.sendRedirect("register.jsp"); 
         }

         try{   
             // 连接到 mongodb 服务
             MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
             //此处采用无用户名和密码验证方式登陆
             @SuppressWarnings("deprecation")
             DB db = mongoClient.getDB( "library" );  //连接到数据库library
             DBCollection coll = db.getCollection("userInfo");  //获取library数据库中集合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页面代码如下:

亚洲必赢官网 17亚洲必赢官网 18

<%@ 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>

View Code

 

2.6.4购入商品

落到实处买卖商品,通过Buy.jsp业务处理脚本调用ShopCartBean.java类来达成。

ShopCartBean.java类代码如下:

package com.liuzhen.shop;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

public class ShopCartBean {

        //ShopCartBean类构造函数
        public ShopCartBean(){

        }

        //定义一个存储整形数值的键值对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,设定购买物品数目,并将购买数目存入哈希表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中物品的数目,以及当前购物车物品总价格
        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();
        } 

        //返回用户购买物品的详细信息(物品编号、物品名称、物品价格、物品购买数量)
        public String[][] getCart()
        {
            //定义一个set集合,存放哈希表hm中键值对的键名称
            Set<String> ks=hm.keySet();
            //定义一个迭代器,用于遍历set集合
            Iterator<String> ii=ks.iterator();
            //获取哈希表hm中键值对的个数
            int size=hm.size();
            //定义二维数组,存放购买物品的信息
            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();   //获取购买货物数量
                rs[i]=sa;       //将上述单个物品详细存入二维数组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>

 

jsp和html都得以正确的显得,当jsp引入html时访问jsp页面html现身乱码,jsp原有的出口无乱码,消除方案:

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页面代码:

亚洲必赢官网 19亚洲必赢官网 20

<%@ 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;">
                     简单购物车系统
                   </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>

View Code

底部bottom.jsp页面代码:

亚洲必赢官网 21亚洲必赢官网 22

<%@ 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>

View Code

首页中间主体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为分页数
//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>

 

福寿绵绵查看商品的成效,首借使因而调用MongodbBean.java类来完结,其实际代码如下:

package com.liuzhen.shop;

import java.util.Map;
import java.util.Vector;

import com.mongodb.*;

public class MongodbBean {

    static int span=5;    //设定JSP页面表单单页显示物品信息行数为5行

    //返回数据库中全部货物编号sid
    public static String[] getGood_sid(){
        String[] good_sid_temporary = new String[100];    //定义一个长度为100的暂时存放货物编号的一维数组    
         // 连接到 mongodb 服务
        MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
        //此处采用无用户名和密码验证方式登陆
        @SuppressWarnings("deprecation")
        DB db = mongoClient.getDB( "library" );  //连接到数据库library
        DBCollection coll = db.getCollection("good");  //获取library数据库中集合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;         //将数据库中查询的货物编号存储入数组good_sid                              
           i++;
         }
        String[] good_sid = new String[i];   //根据查询数据遍历集合中文档信息i值来确定最终返回数组长度
        for(int j=0;j<i;j++){
            good_sid[j] = good_sid_temporary[j];
        }

        return good_sid;
    }

    //返回数据库中全部货物名称sname
    public static String[] getGood_sname(){
        String[] good_sname_temporary = new String[100];  //定义一个长度为100的暂时存放货物名称的一维数组
         // 连接到 mongodb 服务
        MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
        //此处采用无用户名和密码验证方式登陆
        @SuppressWarnings("deprecation")
        DB db = mongoClient.getDB( "library" );  //连接到数据库library
        DBCollection coll = db.getCollection("good");  //获取library数据库中集合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;     //将数据库中查询的货物名称存储入数组good_sname                         
           i++;
        }
        String[] good_sname = new String[i];   //根据查询数据遍历集合中文档信息i值来确定最终返回数组长度
        for(int j=0;j<i;j++){
            good_sname[j] = good_sname_temporary[j];
        }
        return good_sname;
    }

    //返回数据库中全部货物价格sprice
    public static String[] getGood_sprice(){
        String[] good_sprice_temporary = new String[100]; //定义一个长度为100的暂时存放货物价格的一维数组
         // 连接到 mongodb 服务
        MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
        //此处采用无用户名和密码验证方式登陆
        @SuppressWarnings("deprecation")
        DB db = mongoClient.getDB( "library" );  //连接到数据库library
        DBCollection coll = db.getCollection("good");  //获取library数据库中集合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;   //将数组库中查询的货物价格存储入数组good_sprice                     
           i++;
        }
        String[] good_sprice = new String[i];   //根据查询数据遍历集合中文档信息i值来确定最终返回数组长度
        for(int j=0;j<i;j++){
            good_sprice[j] = good_sprice_temporary[j];
        }
        return good_sprice;
    }

    //根据分页当前page数,从数据库中获取当前单个页面货物种类的具体信息,并以二维数据返回具体信息
    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= len){ 
                //如果当前货物编号大于数据库中已有编号,则跳出循环
                break;
            }

            String[] good_temp=new String[3];   //定义一个长度为3的数组,用于存放一个物品的编号、名称、价格信息
            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指定行数大小
        for(int j=0;j<size;j++)
        {
           //返回Vector中一个值(其中即表示一个物品的sid,名称和价格),并赋值给result[j],即result二维数组一行表示一个物品具体信息
            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的数组返回
    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,得到名称存入数组good_detail中
        good_detail[1] = good_sprice[i];       //根据物品编号sid,得到物品价格存入数组good_detail中        

        return good_detail;
    }

    //通过查询数据库中货物种类数目,以5行为一页,返回现有货物页数
    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)行为一页,计算货物具有的页数page

        return page;            
    }



    //返回一个二维数组的行数大小
    public static int getlength(String[][] a){
        return a.length;
    }


    public static void main(String args[]){
//        String[] good_sid = getGood_sid();    //定义一个存放货物编号的一维数组
//        String[] good_sname = getGood_sname();  //定义一个存放货物名称的一维数组
//        String[] good_sprice = getGood_sprice(); //定义一个存放货物价格的一维数组
//                                      
//        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("分页数目(测试):"+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("数组长度为:"+n);


    }


}

 

2.6.5购物车

购物车成效,重假如用过Cart.jsp页面调用ShopCartBean.java类来贯彻,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">数量</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'">继续购物</button>
    </div>
 </div>
 </div>
  </body>
</html>

 

 

附:本系统源码Coding链接:

目录 1 题材讲述 2 消除方案 2.1 达成效益 2.2 最终运转效果图 2.3
系统机能框架示意…

 

2.6.4进货商品

贯彻购销商品,通过Buy.jsp业务处理脚本调用ShopCartBean.java类来落到实处。

ShopCartBean.java类代码如下:

package com.liuzhen.shop;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

public class ShopCartBean {

        //ShopCartBean类构造函数
        public ShopCartBean(){

        }

        //定义一个存储整形数值的键值对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,设定购买物品数目,并将购买数目存入哈希表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中物品的数目,以及当前购物车物品总价格
        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();
        } 

        //返回用户购买物品的详细信息(物品编号、物品名称、物品价格、物品购买数量)
        public String[][] getCart()
        {
            //定义一个set集合,存放哈希表hm中键值对的键名称
            Set<String> ks=hm.keySet();
            //定义一个迭代器,用于遍历set集合
            Iterator<String> ii=ks.iterator();
            //获取哈希表hm中键值对的个数
            int size=hm.size();
            //定义二维数组,存放购买物品的信息
            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();   //获取购买货物数量
                rs[i]=sa;       //将上述单个物品详细存入二维数组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>

 

       
在html第2行参加:<%@ page language=”java” import=”java.util.*”
pageEncoding=”gb18030″%>

2.6.5购物车

购物车效能,首假诺用过Cart.jsp页面调用ShopCartBean.java类来落到实处,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">数量</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'">继续购物</button>
    </div>
 </div>
 </div>
  </body>
</html>

 

 

附:本系统源码Coding链接:

 

 

 


如要借用本文代码的同桌,请做好入坑准备>~<,上边包车型地铁三个bug,笔者立马为了快点完结实验,后来就从不再一次消除这些难题(PS:要以史为鉴本次教训,未来境遇标题要立马消除),完开支篇小说距离写下下边表达已经大约有多少个多月了,自个儿也无意重新跑代码修改bug,所以作出如下两点表达>~<

有关本系统Bug部分表达:

记于2017年4月27日 

1.在分页呈现商品时,假设刚好是15条数据,突显时本人回想会出现数量越界错误

2.点击购买商品时,记得好像是买进物品3,在购物车里展现的却是物品4(PS:此处关键是后台物品的SID数值设置,假如从1始发以来,碰面世这些题材,假设改动为0开头盘算物品SID,就能够健康展现)

化解办法:

针对难题1:

代码部分如下图:

亚洲必赢官网 23

 

亚洲必赢官网 24

 

针对难题2:

亚洲必赢官网 25

 

亚洲必赢官网 26

 

 

       
jsp的编码格式为:<%@ page language=”java” import=”java.util.*”
contentType=”text/html;charset=UTF-8″ pageEncoding=”UTF-8″%>

 1.是因为要求使用数据库来进展判断用户是还是不是登陆,必须供给多个报了名页面
reg.jap

 1 <%@ page language="java" pageEncoding="utf-8"%>
 2 <!DOCTYPE html>
 3 <html>
 4 <head>
 5 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 6 <title>注册页面</title>
 7 <link href="styles/index.css" rel="stylesheet">
 8 </head>
 9 <body>
10 <!-- 文件引入的两种方式 -->
11 <%--  <%@include file="include/header.inc.html"%> --%>
12     <jsp:include page="include/header.inc.html"></jsp:include>
13     <p class="welcome">欢迎进入购物车注册界面</p>
14     <form action="doreg.jsp" method="post">
15         <div>
16             <h2>用户名:</h2><input class="input" type="text" name="username"  placeholder="请输入用户名">
17         </div>
18         <div>
19             <h2>密 码:</h2><input class="input" type="password" name="pwd"  placeholder="请输入您的密码">
20         </div>
21         <div>
22             <input class="input1" type="submit" value="注册"> 
23             <input class="input1" type="reset" value="重置">
24         </div>
25          <h3>已有账号,直接<a href="index.jsp">登陆</a></h3>
26     </form>
27     <%@include file="include/footer.inc.html"%>
28 </body>
29 </html>

2.亟待写贰个数据库来存款和储蓄用户信息,表名为 ·user·;(创造表的语句不写)

+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| uesrname | varchar(20) | NO   |     | NULL    |       |
| password | int(16)     | NO   |     | NULL    |       |
+----------+-------------+------+-----+---------+-------+

2.1  还亟需2个表来存款和储蓄商品信息 goods 表

 create table `goods1` (id int not null auto_increment primary key,goods_name varchar(20), goodspic varchar(30),goods_pri double(10), goods_name_en varchar(20))engine = InnoDB default charset=utf8; 

+---------------+-------------+------+-----+---------+----------------+
| Field         | Type        | Null | Key | Default | Extra          |
+---------------+-------------+------+-----+---------+----------------+
| id            | int(11)     | NO   | PRI | NULL    | auto_increment |
| goods_name    | varchar(20) | YES  |     | NULL    |                |
| goodspic      | varchar(30) | YES  |     | NULL    |                |
| goods_pri     | varchar(20) | YES  |     | NULL    |                |
| goods_name_en | varchar(20) | YES  |     | NULL    |                |
+---------------+-------------+------+-----+---------+----------------+

3.用户注册的音讯以post 的主意交给给doreg.jsp来处理
,注册成功即跳转商品页面goods.jsp

 1 <%@page import="java.sql.*"%>
 2 <%@ page language="java" pageEncoding="GB18030"%>
 3 
 4 <%
 5 try{
 6     Class.forName("com.mysql.jdbc.Driver");//加载数据库驱动,注册到驱动管理器
 7     String url = "jdbc:mysql://127.0.0.1:3301/shopcar";//数据库连接字符串
 8     String usename = "root";
 9     String password = "123456";
10     Connection conn = DriverManager.getConnection(url,usename,password);//创建Connection连接
11     if(conn != null){
12         System.out.println("数据库链接成功!");
13         //conn.close();//关闭数据库连接
14         String insert_db = "INSERT INTO `user`(uesrname,password)values(?,?)";
15         //插入操作
16         PreparedStatement statement = (PreparedStatement)conn.prepareStatement(insert_db);
17         
18         statement.setString(1,request.getParameter("username"));
19         statement.setString(2,request.getParameter("pwd"));
20         statement.executeUpdate();
21         
22         session.setAttribute("userName", request.getParameter("username"));//给当前注册用户开启会话
23         out.println("插入成功");
24         out.println("页面在3秒钟内自动跳转");
25         out.println("<a href=\"goods.jsp\">点击请进入购物页面</a>");
26     }else{
27         out.println("数据库连接失败");//输出错误信息
28     }
29 }catch(ClassNotFoundException e){
30     e.printStackTrace();
31 }catch(SQLException e){
32     e.printStackTrace();
33 }
34 %>
35 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
36 <html>
37 <head>
38 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
39 <meta http-equiv="refresh" content="2;url=goods.jsp"> 
40 <title>注册页面</title>
41 </head>
42 <body>
43 
44 </body>
45 </html>

4.已有账户的用户向来登陆举行,index.jsp

 1 <%@ page language="java" import="java.util.*"
 2     contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>
 3 
 4 <%
 5     Cookie[] cookies = request.getCookies();
 6     String uname = "";
 7     String upwd = "";
 8     String utrue = "";
 9     if(cookies != null ){
10         for(int i = 0 ; i < cookies.length; i++){
11             Cookie cookie = cookies[i];
12             if(cookie.getName().equals("rname")){
13                 uname = cookie.getValue();
14             }else if(cookie.getName().equals("rpwd")){
15                 upwd = cookie.getValue();
16             }else if(cookie.getName().equals("rtrue")){
17                 utrue = cookie.getValue();
18             }
19         }
20     }
21 %>
22 
23 
24 <!DOCTYPE html>
25 <html>
26 <head>
27 <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
28 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
29 <title>欢迎进入购物车</title>
30 <link href="styles/index.css" rel="stylesheet">
31 </head>
32 <body>
33     <%-- <%@include file="include/header.inc.html"%> --%>
34     <jsp:include page="include/header.inc.html"></jsp:include>
35     <p class="welcome">欢迎进入购物车登陆界面</p>
36     <form action="show.jsp">
37         <div>
38             <h2>用户名:</h2><input class="input" type="text" name="username" value="<%= uname %>" placeholder="请输入用户名">
39         </div>
40         <div>
41             <h2>密 码:</h2><input class="input" type="password" name="pwd" value="<%= upwd %>" placeholder="请输入您的密码">
42         </div>
43         <div>
44             <input type="checkbox" name="remember" value="true"> <input class="input1"
45                 type="submit" value="登陆"> <input class="input1" type="reset" value="重置">
46         </div>
47         <div><p>还没有注册,请先注册</p>  
48              <a href="reg.jsp">注册</a>
49         </div>
50     </form>
51     <%@include file="include/footer.inc.html"%>
52 </body>
53 </html>

5.检查和测试登陆结果用show.jsp来注脚。

 1 <%@page import="java.sql.*"%>
 2 <%@ page language="java" contentType="text/html; charset=GB18030"
 3     pageEncoding="GB18030"%>
 4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 5 <html>
 6 <head>
 7 <meta http-equiv="Content-Type" content="text/html; charset=GB18030">
 8 <title>Insert title here</title>
 9 </head>
10 <body>
11     <%
12     
13     String username = request.getParameter("username");
14     String password = request.getParameter("pwd");
15     String remember = request.getParameter("remember");
16 
17     if(username == null)
18         username="";
19     if(password == null)
20         password="";
21     if(remember == null)
22         remember = "false";
23     
24     String driver = "com.mysql.jdbc.Driver";
25     String url = "jdbc:mysql://127.0.0.1:3301/shopcar";
26     String user = "root";
27     String password_db = "123456";
28     try {
29         Class.forName(driver);//加载驱动
30         Connection conn = DriverManager.getConnection(url,user,password_db);
31         // 连接URL为 jdbc:mysql://服务器地址/数据库名 ,后面的2个参数分别是登陆用户名和密码        
32         System.out.println("Success connect Mysql server!");
33         // statement用来执行SQL语句
34         Statement stmt = conn.createStatement();
35         // 结果集
36         ResultSet rs = stmt.executeQuery("select * from `user`");
37         // student 为你表的名称
38         while (rs.next()) {
39             String name = rs.getString("uesrname");
40             String pwd = rs.getString("password");
41             /* out.println(rs.getString("uesrname"));
42             out.println(rs.getString("password")+"<br>"); */
43             if(username!=null && username.equals(name) && password.equals(pwd))
44             {
45                 if(remember != null && remember.equals("true"))
46                 {
47                     Cookie cookie1 = new Cookie("rname",username);
48                     Cookie cookie2 = new Cookie("rpwd",password);
49                     cookie1.setMaxAge(60*60*24*7);
50                     cookie2.setMaxAge(60*60*24*7);
51                     response.addCookie(cookie1);
52                     response.addCookie(cookie2);
53                 }
54                 session.setAttribute("userName",username);
55                 response.sendRedirect("goods.jsp");
56             }else{
57                 /* response.sendRedirect("index.jsp"); */
58                 out.println("查询不成功");
59                 /* out.println("<a href = \"index.jsp\">请重新登陆</a>"); */
60             }
61             
62         }
63     } catch (Exception e) {
64         // TODO: handle exception
65         System.out.print("get data error!");
66         e.printStackTrace();
67     }
68     
69     
70     
71 
72     
73     %>
74 </body>
75 </html>

6.中标登陆进入商品选取页面,从数据库中调集数据goods1.jsp (6.1
为未用数据库显示的商品采纳页面,能够先参考6.1)

<%@page import="java.sql.*"%>
<%@ page language="java" pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>购物页面</title>
<style>
    td{border:1px solid green;}
</style>
</head>
<body>
 <!--创建数据表 create table `goods` (id int not null auto_increment primary key,goods_name varchar(20), goodspic varchar(30),goods_pri varchar(20), goods_name_en varchar(20)); -->
<p>欢迎用户:
<%= 
    session.getAttribute("userName")
%>
</p>
<p>请选购商品并填写所需要购买的数量</p>
<form action="order2.jsp" method="post">
    <table style="border:1px solid green;">
        <thead>
            <tr>
                <th>编号</th>
                <th>商品名</th>
                <th>单价</th>
                <th>购买数量</th>
            </tr>
        </thead>
        <tbody>

<%
try{
    Class.forName("com.mysql.jdbc.Driver");//加载数据库驱动,注册到驱动管理器
    String url = "jdbc:mysql://127.0.0.1:3301/shopcar";//数据库连接字符串
    String usename = "root";
    String password = "123456";
    Connection conn = DriverManager.getConnection(url,usename,password);//创建Connection连接
    // statement用来执行SQL语句
    Statement stmt = conn.createStatement();
    // 结果集
    ResultSet rs = stmt.executeQuery("select * from `goods1`");
    // student 为你表的名称
    while (rs.next()) {
        application.setAttribute("id", rs.getString("id"));
        application.setAttribute("goods_name", rs.getString("goods_name"));
        application.setAttribute("goodspic", rs.getString("goodspic"));
        application.setAttribute("goods_pri", rs.getString("goods_pri"));
        application.setAttribute("goods_name_en", rs.getString("goods_name_en"));
        /* String id = (rs.getString("id"));
        String goods_name = (rs.getString("goods_name"));
        String goodspic = (rs.getString("goodspic"));
        String goods_pri = (rs.getString("goods_pri"));
        String goods_name_en = (rs.getString("goods_name_en")); */
%>
        <tr>
            <td><%=application.getAttribute("id") %></td>
            <td><img src="<%=application.getAttribute("goodspic") %>"><%=application.getAttribute("goods_name") %></td>
            <td>¥<%=application.getAttribute("goods_pri") %></td>
            <td><input type="text" name="<%=application.getAttribute("goods_name_en") %>" id="" value="" placeholder="0"></td>
        </tr>
<%        

        }

    }catch(ClassNotFoundException e){
        e.printStackTrace();
    }catch(SQLException e){
        e.printStackTrace();
    }
%>

            </tbody>
        </table>
        <input type="submit" value="提交订单">
    </form>
</body>
</html>

6.1 未用数据库的代码 goods.jsp

 1 <%@ page language="java" contentType="text/html; charset=utf-8"
 2     pageEncoding="GB18030"%>
 3 <!DOCTYPE html>
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 7 <title>购物页面</title>
 8 <style>
 9     td{border:1px solid green;}
10 </style>
11 </head>
12 <body>
13  <!--创建数据表 create table `goods` (id int not null auto_increament primary key,goods_name varchar(20), goodspic varchar(30),goods_name_en varchar(20)); -->
14     <p>欢迎用户:
15     <%= 
16         session.getAttribute("userName")
17     %>
18     </p>
19     <p>请选购商品并填写所需要购买的数量</p>
20     <form action="order.jsp" method="post">
21         <table style="border:1px solid green;">
22             <thead>
23                 <tr>
24                     <th>编号</th>
25                     <th>商品名</th>
26                     <th>单价</th>
27                     <th>购买数量</th>
28                 </tr>
29             </thead>
30             <tbody>
31                 <tr>
32                     <td>1</td>
33                     <td><img src=".pple.jpg"/>苹果</td>
34                     <td>¥5.0</td>
35                     <td><input type="text" name="apple" id="" placeholder="0"></td>
36                 </tr>
37                 <tr>
38                     <td>2</td>
39                     <td><img src=".orange.jpg"/>橘子</td>
40                     <td>¥3.0</td>
41                     <td><input type="text" name="orange" id="" placeholder="0"></td>
42                 </tr>
43                 <tr>
44                     <td>3</td>
45                     <td><img src=".nana.jpg"/>香蕉</td>
46                     <td>¥2.0</td>
47                     <td><input type="text" name="banana" id="" placeholder="0"></td>
48                 </tr>
49                 <tr>
50                     <td>4</td>
51                     <td><img src=".youzi.jpg"/>柚子</td>
52                     <td>¥4.5</td>
53                     <td><input type="text" name="grapefruit" id="" placeholder="0"></td>
54                 </tr>
55                 <tr>
56                     <td>5</td>
57                     <td><img src=".peach.jpg"/>桃子</td>
58                     <td>¥5.5</td>
59                     <td><input type="text" name="peach" id="" placeholder="0"></td>
60                 </tr>
61             </tbody>
62         </table>
63         <input type="submit" value="提交订单">
64         <!-- <button type="submit">提交订单</button> -->
65     </form>
66 </body>
67 </html>

7.预约结果order.jsp展现页面,运用javaBean来总结,将逻辑分离

亚洲必赢官网 27亚洲必赢官网 28

 1 <%@ page language="java" contentType="text/html; charset=utf-8"
 2     pageEncoding="GB18030"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 7 <title>订单信息</title>
 8 </head>
 9 <body>
10      <jsp:useBean id="car" scope="page" class="ShopCar.CountPrice">
11             <jsp:setProperty name="car" property="num_apple" param="apple"/>
12             <jsp:setProperty name="car" property="num_orange" param="orange"/>
13             <jsp:setProperty name="car" property="num_banana" param="banana"/>
14             <jsp:setProperty name="car" property="num_grapefruit" param="grapefruit"/>
15             <jsp:setProperty name="car" property="num_peach" param="peach"/>
16             <p><b>尊敬的用户:</b></p>
17         <%= 
18             session.getAttribute("userName")
19         %>
20             <p>您选购的订单详情如下</p>
21         <table>
22             <thead>
23                 <tr><th>编号</th><th>商品名</th><th>单价</th><th>购买数量</th><th>价格</th></tr>
24             </thead>
25             <tbody>
26                 <tr>
27                     <td>1</td>
28                     <td>苹果</td>
29                     <td>¥5.0</td>
30                     <td><jsp:getProperty name = "car" property="num_apple" /></td>
31                     <td><jsp:getProperty name = "car" property="pri_apple" /></td>
32                 </tr>
33                 <tr>
34                     <td>2</td>
35                     <td>橘子</td>
36                     <td>¥3.0</td>
37                     <td><jsp:getProperty name = "car" property="num_orange" /></td>
38                     <td><jsp:getProperty name = "car" property="pri_orange" /></td>
39                 </tr>
40                 <tr>
41                     <td>3</td>
42                     <td>香蕉</td>
43                     <td>¥2.0</td>
44                     <td><jsp:getProperty name = "car" property="num_banana" /></td>
45                     <td><jsp:getProperty name = "car" property="pri_banana" /></td>
46                 </tr>
47                 <tr>
48                     <td>4</td>
49                     <td>柚子</td>
50                     <td>¥4.5</td>
51                     <td><jsp:getProperty name = "car" property="num_grapefruit" /></td>
52                     <td><jsp:getProperty name = "car" property="pri_grapefruit" /></td>
53                 </tr>
54                 <tr>
55                     <td>5</td>
56                     <td>桃子</td>
57                     <td>¥5.5</td>
58                     <td><jsp:getProperty name = "car" property="num_peach" /></td>
59                     <td><jsp:getProperty name = "car" property="pri_peach" /></td>
60                 </tr>
61             </tbody>
62         </table>
63         <div>总价为:<jsp:getProperty  name="car" property="total_price"/></div>
64         <button>立即付款</button>
65         <a href="goods.jsp"><button>取消订单</button></a>
66      </jsp:useBean>
67 </body>
68 </html>

View Code

8.javaBean的计量代码ShopCar.Count普赖斯

亚洲必赢官网 29亚洲必赢官网 30

  1 package ShopCar;
  2 
  3 public class CountPrice {
  4     private double num_apple;
  5     private double num_orange;
  6     private double num_banana;
  7     private double num_grapefruit;
  8     private double num_peach;
  9     private double pri_apple;
 10     private double pri_orange;
 11     private double pri_banana;
 12     private double pri_grapefruit;
 13     private double pri_peach;
 14     private double total_price;
 15 
 16     public double getNum_apple() {
 17         return num_apple;
 18     }
 19 
 20     public void setNum_apple(double num_apple) {
 21         this.num_apple = num_apple;
 22         this.setPri_apple(num_apple * 5.0);
 23     }
 24 
 25     public double getNum_orange() {
 26         return num_orange;
 27     }
 28 
 29     public void setNum_orange(double num_orange) {
 30         this.num_orange = num_orange;
 31         this.setPri_orange(num_orange * 3.0);
 32     }
 33 
 34     public double getNum_banana() {
 35         return num_banana;
 36 
 37     }
 38 
 39     public void setNum_banana(double num_banana) {
 40         this.num_banana = num_banana;
 41         this.setPri_banana(num_banana * 2.0);
 42     }
 43 
 44     public double getNum_grapefruit() {
 45         return num_grapefruit;
 46     }
 47 
 48     public void setNum_grapefruit(double num_grapefruit) {
 49         this.num_grapefruit = num_grapefruit;
 50         this.setPri_grapefruit(num_grapefruit * 4.5);
 51     }
 52 
 53     public double getNum_peach() {
 54         return num_peach;
 55     }
 56 
 57     public void setNum_peach(double num_peach) {
 58         this.num_peach = num_peach;
 59         this.setPri_peach(num_peach * 5.5);
 60     }
 61 
 62     public double getPri_apple() {
 63         return pri_apple;
 64     }
 65 
 66     public void setPri_apple(double pri_apple) {
 67         this.pri_apple = pri_apple;
 68     }
 69 
 70     public double getPri_orange() {
 71         return pri_orange;
 72     }
 73 
 74     public void setPri_orange(double pri_orange) {
 75         this.pri_orange = pri_orange;
 76     }
 77 
 78     public double getPri_banana() {
 79         return pri_banana;
 80     }
 81 
 82     public void setPri_banana(double pri_banana) {
 83         this.pri_banana = pri_banana;
 84     }
 85 
 86     public double getPri_grapefruit() {
 87         return pri_grapefruit;
 88     }
 89 
 90     public void setPri_grapefruit(double pri_grapefruit) {
 91         this.pri_grapefruit = pri_grapefruit;
 92     }
 93 
 94     public double getPri_peach() {
 95         return pri_peach;
 96     }
 97 
 98     public void setPri_peach(double pri_peach) {
 99         this.pri_peach = pri_peach;
100     }
101 
102     public double getTotal_price() {
103         this.total_price = this.getPri_apple() + this.getPri_banana()
104                 + this.getPri_grapefruit() + this.getPri_grapefruit()
105                 + this.getPri_orange() + this.getPri_peach();
106         return total_price;
107     }
108 }

View Code

亚洲必赢官网 31

亚洲必赢官网 32

亚洲必赢官网 33

 附:此次实验还有为数不少不周全的地点,开销了较长的小运,不想总括,饿了!!!

网站地图xml地图