利用JSP编程技术实现一个简单的购物车程序

时间:2024-03-10 14:20:58

实验二   JSP编程

.实验目的1. 掌握JSP指令的使用方法;2. 掌握JSP动作的使用方法;3. 掌握JSP内置对象的使用方法;4. 掌握JavaBean的编程技术及使用方法;5. 掌握JSP数据库编程方法;

 二.实验要求 : 利用JSP编程技术实现一个简单的购物车程序,具体要求如下。

1)用JSP编写一个登录页面,登录信息中有用户名和密码,分别用两个按钮来提交和重置登录信息。

2)编写一个JSP程序来处理用户提交的登录信息,如果用户名为本小组成员的名字且密码为对应的学号时,采用JSP内置对象的方法跳转到订购页面(显示店中商品的种类和单价等目录信息);否则采用JSP动作提示用户重新登录(注:此页面上要包含前面的登录界面)

3)当顾客填好所需商品的数量并点击提交按钮时,将前面订购的商品放入购物车中并显示购物车里的相关信息,包括商品的名称和数量以及所有商品的总价格(关于总价格的计算,要求通过编写一个JavaBean来辅助实现)。

4修改登录程序。将合法用户信息(用户名)写入数据库中,登录时通过查找数据库来完成登录 

5)将商品信息写入数据库,计算价格时通过查找数据库来完成。

 

 

 

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

 

jsp和html都可以正确的显示,当jsp引入html时访问jsp页面html出现乱码,jsp原有的输出无乱码,解决方案:

 

        在html第一行加入:<%@ page language="java" import="java.util.*" pageEncoding="gb18030"%>

 

        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  还需要一个表来存储商品信息 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="./images/apple.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="./images/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="./images/banana.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="./images/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="./images/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来计算,将逻辑分离

 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.CountPrice

  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

 附:本次实验还有很多不完善的地方,花费了较长的时间,不想总结,饿了!!!