首页 > 技术文章 > java EE 网上书店 —— 核心代码实现

dashuaiB 2019-05-29 23:44 原文

介绍

  项目采用B/S架构、MVC开发模式,使用java语言,根据Java EE 标准开发,旨在感受java web项目开发流程、学习与理解java EE基础技术和原理。

M: Model模型 JavaBean
V:view视图 Html
C:Controller控制器 Servlet

其中Html与Servlet之间用Ajax与Json技术互动。


 项目结构

使用maven构建,分为Dao、Service、Servlet、和前端展示层

 


数据持久化工具

使用C3p0数据库连接池

C3P0配置文件出c3p0-config.xml:

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
    <default-config>
        <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/数据库名?serverTimezone=Asia/Shanghai</property>
        <property name="user">用户名</property>
        <property name="password">密码</property>
        <!-- 初始化连接的数量 -->
        <property name="initialPoolSize">10</property>
        <!-- 最大空闲时间,单位是秒 -->
        <property name="maxIdleTime">1</property>
        <!-- 池中最大连接的数量 -->
        <property name="maxPoolSize">100</property>
        <!-- 池中最小连接的数量 -->
        <property name="minPoolSize">10</property>
    </default-config>
</c3p0-config>
复制代码

C3P0Util:

复制代码
package util;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * C3P0
 */
public class C3P0Util {
    // 得到一个c3p0的数据源
    private static ComboPooledDataSource dataSource = new ComboPooledDataSource();

    // 从数据源中得到一个连接对象
    // 这个返回的connection实际上是c3p0经过装饰之后的connection
    public static Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException("服务器错误");
        }
    }

    //查看连接池的状态
    public static void poolStatus() {
        try {
            System.out.println("清闲的:" + dataSource.getNumIdleConnections());
            System.out.println("忙碌的:" + dataSource.getNumBusyConnections());
            System.out.println("所有的:" + dataSource.getNumConnections());
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
}
复制代码

 


实体映射

User:

复制代码
  1 package bean;
  2 
  3 import java.util.Date;
  4 
  5 public class User {
  6     private int id;
  7     private String username;
  8     private String password;
  9     private String email;
 10     private String realname;
 11     private String address;
 12     private String mobile;
 13     private Date regTime;
 14     private int role;
 15 
 16     public int getId() {
 17         return id;
 18     }
 19 
 20     public void setId(int id) {
 21         this.id = id;
 22     }
 23 
 24     public String getUsername() {
 25         return username;
 26     }
 27 
 28     public void setUsername(String username) {
 29         this.username = username;
 30     }
 31 
 32     public String getPassword() {
 33         return password;
 34     }
 35 
 36     public void setPassword(String password) {
 37         this.password = password;
 38     }
 39 
 40     public String getEmail() {
 41         return email;
 42     }
 43 
 44     public void setEmail(String email) {
 45         this.email = email;
 46     }
 47 
 48     public String getRealname() {
 49         return realname;
 50     }
 51 
 52     public void setRealname(String realname) {
 53         this.realname = realname;
 54     }
 55 
 56     public String getAddress() {
 57         return address;
 58     }
 59 
 60     public void setAddress(String address) {
 61         this.address = address;
 62     }
 63 
 64     public String getMobile() {
 65         return mobile;
 66     }
 67 
 68     public void setMobile(String mobile) {
 69         this.mobile = mobile;
 70     }
 71 
 72     public Date getRegTime() {
 73         return regTime;
 74     }
 75 
 76     public void setRegTime(Date regTime) {
 77         this.regTime = regTime;
 78     }
 79 
 80     public int getRole() {
 81         return role;
 82     }
 83 
 84     public void setRole(int role) {
 85         this.role = role;
 86     }
 87 
 88     @Override
 89     public String toString() {
 90         return "User{" +
 91                 "id=" + id +
 92                 ", username='" + username + '\'' +
 93                 ", password='" + password + '\'' +
 94                 ", email='" + email + '\'' +
 95                 ", realname='" + realname + '\'' +
 96                 ", address='" + address + '\'' +
 97                 ", mobile='" + mobile + '\'' +
 98                 ", regTime=" + regTime +
 99                 ", role=" + role +
100                 '}';
101     }
102 }
复制代码

Book:

复制代码
  1 package bean;
  2 
  3 import java.math.BigDecimal;
  4 
  5 public class Book {
  6     private int id;
  7     private String bookname;
  8     private int salesVolume;
  9     private int inventory;
 10     private int categoryId;
 11     private String depict;
 12     private BigDecimal price;
 13     private BigDecimal sellingPrice;
 14     private int recommend;
 15     private int clickcount;
 16     private int onSale;
 17     private String imgAddress;
 18     
 19     public int getId() {
 20         return id;
 21     }
 22 
 23     public void setId(int id) {
 24         this.id = id;
 25     }
 26 
 27     public String getBookname() {
 28         return bookname;
 29     }
 30 
 31     public void setBookname(String bookname) {
 32         this.bookname = bookname;
 33     }
 34 
 35     public int getSalesVolume() {
 36         return salesVolume;
 37     }
 38 
 39     public void setSalesVolume(int salesVolume) {
 40         this.salesVolume = salesVolume;
 41     }
 42 
 43     public int getInventory() {
 44         return inventory;
 45     }
 46 
 47     public void setInventory(int inventory) {
 48         this.inventory = inventory;
 49     }
 50 
 51     public int getCategoryId() {
 52         return categoryId;
 53     }
 54 
 55     public void setCategoryId(int categoryId) {
 56         this.categoryId = categoryId;
 57     }
 58 
 59     public String getDepict() {
 60         return depict;
 61     }
 62 
 63     public void setDepict(String depict) {
 64         this.depict = depict;
 65     }
 66 
 67     public BigDecimal getPrice() {
 68         return price;
 69     }
 70 
 71     public void setPrice(BigDecimal price) {
 72         this.price = price;
 73     }
 74 
 75     public BigDecimal getSellingPrice() {
 76         return sellingPrice;
 77     }
 78 
 79     public void setSellingPrice(BigDecimal sellingPrice) {
 80         this.sellingPrice = sellingPrice;
 81     }
 82 
 83     public int getRecommend() {
 84         return recommend;
 85     }
 86 
 87     public void setRecommend(int recommend) {
 88         this.recommend = recommend;
 89     }
 90 
 91     public int getClickcount() {
 92         return clickcount;
 93     }
 94 
 95     public void setClickcount(int clickcount) {
 96         this.clickcount = clickcount;
 97     }
 98 
 99     public int getOnSale() {
100         return onSale;
101     }
102 
103     public void setOnSale(int onSale) {
104         this.onSale = onSale;
105     }
106 
107     public String getImgAddress() {
108         return imgAddress;
109     }
110 
111     public void setImgAddress(String imgAddress) {
112         this.imgAddress = imgAddress;
113     }
114 
115     @Override
116     public String toString() {
117         return "Book{" +
118                 "id=" + id +
119                 ", bookname='" + bookname + '\'' +
120                 ", salesVolume=" + salesVolume +
121                 ", inventory=" + inventory +
122                 ", categoryId=" + categoryId +
123                 ", depict='" + depict + '\'' +
124                 ", price=" + price +
125                 ", sellingPrice=" + sellingPrice +
126                 ", recommend=" + recommend +
127                 ", clickcount=" + clickcount +
128                 ", onSale=" + onSale +
129                 ", imgAddress='" + imgAddress + '\'' +
130                 '}';
131     }
132 }
复制代码

ShopCart:

复制代码
 1 package bean;
 2 
 3 import java.math.BigDecimal;
 4 
 5 public class ShopCart {
 6     private int id;
 7     private int bookId;
 8     private int userId;
 9     private int bookCount;
10     //不存在数据库中的属性
11     private String bookName;
12     private BigDecimal unitPrice;
13     BigDecimal totalPrice = BigDecimal.valueOf(0.0);
14     
15     
16     public int getId() {
17         return id;
18     }
19 
20     public void setId(int id) {
21         this.id = id;
22     }
23 
24     public int getBookId() {
25         return bookId;
26     }
27 
28     public void setBookId(int bookId) {
29         this.bookId = bookId;
30     }
31 
32     public int getUserId() {
33         return userId;
34     }
35 
36     public void setUserId(int userId) {
37         this.userId = userId;
38     }
39 
40     public int getBookCount() {
41         return bookCount;
42     }
43 
44     public void setBookCount(int bookCount) {
45         this.bookCount = bookCount;
46     }
47     
48     public String getBookName() {
49         return bookName;
50     }
51     
52     public void setBookName(String bookName) {
53         this.bookName = bookName;
54     }
55     
56     public BigDecimal getUnitPrice() {
57         return unitPrice;
58     }
59 
60     public void setUnitPrice(BigDecimal unitPrice) {
61         this.unitPrice = unitPrice;
62     }
63 
64     public BigDecimal getTotalPrice() {
65         return totalPrice;
66     }
67 
68     public void setTotalPrice(BigDecimal totalPrice) {
69         this.totalPrice = totalPrice;
70     }
71 
72     @Override
73     public String toString() {
74         return "ShopCart{" +
75                 "id=" + id +
76                 ", bookId=" + bookId +
77                 ", userId=" + userId +
78                 ", bookCount=" + bookCount +
79                 ", bookName='" + bookName + '\'' +
80                 ", unitPrice=" + unitPrice +
81                 ", totalPrice=" + totalPrice +
82                 '}';
83     }
84 
85 }
复制代码

Order:

复制代码
 1 package bean;
 2 
 3 import java.math.BigDecimal;
 4 
 5 public class Order {
 6     private String id;
 7     private String address;
 8     private String mobile;
 9     private BigDecimal totalPrice;
10     private String createTime;
11     private String paymentWay;
12     private String orderState;
13     private int userId;
14 
15     public String getId() {
16         return id;
17     }
18 
19     public void setId(String id) {
20         this.id = id;
21     }
22 
23     public String getAddress() {
24         return address;
25     }
26 
27     public void setAddress(String address) {
28         this.address = address;
29     }
30 
31     public String getMobile() {
32         return mobile;
33     }
34 
35     public void setMobile(String mobile) {
36         this.mobile = mobile;
37     }
38 
39     public BigDecimal getTotalPrice() {
40         return totalPrice;
41     }
42 
43     public void setTotalPrice(BigDecimal totalPrice) {
44         this.totalPrice = totalPrice;
45     }
46 
47     public String getCreateTime() {
48         return createTime;
49     }
50 
51     public void setCreateTime(String createTime) {
52         this.createTime = createTime;
53     }
54 
55     public String getPaymentWay() {
56         return paymentWay;
57     }
58 
59     public void setPaymentWay(String paymentWay) {
60         this.paymentWay = paymentWay;
61     }
62 
63     public String getOrderState() {
64         return orderState;
65     }
66 
67     public void setOrderState(String orderState) {
68         this.orderState = orderState;
69     }
70 
71     public int getUserId() {
72         return userId;
73     }
74 
75     public void setUserId(int userId) {
76         this.userId = userId;
77     }
78 
79     @Override
80     public String toString() {
81         return "Order{" +
82                 "id=" + id +
83                 ", address='" + address + '\'' +
84                 ", mobile='" + mobile + '\'' +
85                 ", totalPrice=" + totalPrice +
86                 ", createTime=" + createTime +
87                 ", paymentWay='" + paymentWay + '\'' +
88                 ", orderState='" + orderState + '\'' +
89                 ", userId=" + userId +
90                 '}';
91     }
92 }
复制代码

OrderItem:

复制代码
 1 package bean;
 2 
 3 import java.math.BigDecimal;
 4 
 5 public class OrderItem {
 6    private int id;
 7    private String bookName;
 8    private int bookCount;
 9    private String belongTo;
10    //数据库里没有的属性
11     BigDecimal totalPrice = BigDecimal.valueOf(0.0);
12 
13     public int getId() {
14         return id;
15     }
16 
17     public void setId(int id) {
18         this.id = id;
19     }
20 
21     public String getBookName() {
22         return bookName;
23     }
24 
25     public void setBookName(String bookName) {
26         this.bookName = bookName;
27     }
28 
29     public int getBookCount() {
30         return bookCount;
31     }
32 
33     public void setBookCount(int bookCount) {
34         this.bookCount = bookCount;
35     }
36 
37     public String getBelongTo() {
38         return belongTo;
39     }
40 
41     public void setBelongTo(String belongTo) {
42         this.belongTo = belongTo;
43     }
44 
45     public BigDecimal getTotalPrice() {
46         return totalPrice;
47     }
48 
49     public void setTotalPrice(BigDecimal totalPrice) {
50         this.totalPrice = totalPrice;
51     }
52 
53     @Override
54     public String toString() {
55         return "OrderItem{" +
56                 "id=" + id +
57                 ", bookName='" + bookName + '\'' +
58                 ", bookCount=" + bookCount +
59                 ", belongTo=" + belongTo +
60                 '}';
61     }
62 }
复制代码

 

回到顶部


登陆注册模块

RegistServlet:

复制代码
 1 package servlet;
 2 
 3 import bean.User;
 4 import org.apache.commons.beanutils.BeanUtils;
 5 import service.UserService;
 6 import service.impl.UserServiceImpl;
 7 import javax.servlet.annotation.WebServlet;
 8 import java.io.IOException;
 9 import java.lang.reflect.InvocationTargetException;
10 
11 @WebServlet("/RegistServlet")
12 public class RegistServlet extends javax.servlet.http.HttpServlet {
13     protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
14         doGet(request, response);
15     }
16 
17     protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
18 
19         //将表单提交的数据放在User类中
20         User u = new User();
21         //使用commons-beanutils将表单数据封装到User对象中
22         try {
23             BeanUtils.populate(u, request.getParameterMap());
24         } catch (IllegalAccessException e1) {
25             e1.printStackTrace();
26         } catch (InvocationTargetException e1) {
27             e1.printStackTrace();
28         }
29 
30         if(u.getUsername() == null || u.getUsername() == "" || u.getPassword() == null || u.getPassword() == ""){
31             response.getWriter().write("用户名和密码不能为空!1秒后重新注册");
32             response.setHeader("refresh", "1;url=" + request.getContextPath()
33                     + "/regist.html");
34         } else {
35             //调用业务逻辑
36             UserService us = new UserServiceImpl();
37             try {
38                 //判断用户名是否重复
39                 String result = us.judgeUsername(u);
40 
41                 if(result.equals("true")){   //说明用户名重复
42                     response.getWriter().write("用户名重复!注册失败!1秒后返回");
43                     response.setHeader("refresh", "1;url=" + request.getContextPath()
44                             + "/regist.html");
45                 }else{
46                     //用户名不重复时,执行添加操作
47                     us.addUser(u);
48                     //分发转向
49                     response.getWriter().write("注册成功!1秒跳转到登录页");
50                     response.setHeader("refresh", "1;url=" + request.getContextPath()
51                             + "/login.html");
52                 }
53             } catch (Exception e) {
54                 e.printStackTrace();
55             }
56         }
57 
58     }
59 }
复制代码

LoginServlet:

复制代码
 1 package servlet;
 2 
 3 import bean.User;
 4 import org.apache.commons.beanutils.BeanUtils;
 5 import service.UserService;
 6 import service.impl.UserServiceImpl;
 7 import util.C3P0Util;
 8 
 9 
10 import javax.servlet.ServletException;
11 import javax.servlet.annotation.WebServlet;
12 import javax.servlet.http.HttpServlet;
13 import javax.servlet.http.HttpServletRequest;
14 import javax.servlet.http.HttpServletResponse;
15 import java.io.IOException;
16 import java.lang.reflect.InvocationTargetException;
17 
18 @WebServlet("/LoginServlet")
19 public class LoginServlet extends HttpServlet {
20     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
21         doGet(request, response);
22     }
23 
24     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
25 
26         //查看一下conn状态
27         C3P0Util.poolStatus();
28 
29         User user = new User();
30 
31         try {
32             BeanUtils.populate(user, request.getParameterMap());
33         } catch (IllegalAccessException e1) {
34             // TODO Auto-generated catch block
35         } catch (InvocationTargetException e1) {
36             e1.printStackTrace();
37         }
38 
39         System.out.println("findUserBy:" + user.getUsername() + " " + user.getPassword());
40 
41         UserService us = new UserServiceImpl();
42 
43         System.out.println("路径:" + request.getSession().getServletContext().getRealPath("index.html"));
44         try {
45             User u = us.findUserByUsernameAndPassword(user);
46 
47             //分发转向
48             if(u!=null){
49                 System.out.println("登陆");
50                 //如果登录成功,就把user对象放到session对象中
51                 request.getSession().setAttribute("user", u);
52                 response.sendRedirect("/index.html");
53             }else{
54 
55                 response.getWriter().write("用户名或密码不正确!1秒后重新登陆");
56                 response.setHeader("refresh", "1;url=" + request.getContextPath()
57                         + "/login.html");
58             }
59         } catch (Exception e) {
60             e.printStackTrace();
61         }
62     }
63 }
复制代码

LogoutServlet:

复制代码
 1 package servlet;
 2 
 3 import javax.servlet.ServletException;
 4 import javax.servlet.annotation.WebServlet;
 5 import javax.servlet.http.HttpServlet;
 6 import javax.servlet.http.HttpServletRequest;
 7 import javax.servlet.http.HttpServletResponse;
 8 import java.io.IOException;
 9 
10 @WebServlet("/LogoutServlet")
11 public class LogoutServlet extends HttpServlet {
12     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
13         doGet(request, response);
14     }
15 
16     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
17         //使用sessions销毁
18         request.getSession().invalidate();
19         //重定向到主页
20         response.sendRedirect("/index.html");
21     }
22 }
复制代码

UserServiceImpl:

复制代码
 1 package service.impl;
 2 
 3 import bean.User;
 4 import dao.UserDao;
 5 import dao.impl.UserDaoImpl;
 6 import service.UserService;
 7 
 8 public class UserServiceImpl implements UserService {
 9 
10     UserDao userDao = new UserDaoImpl();
11 
12     @Override
13     public void addUser(User user) throws Exception {
14         userDao.addUser(user);
15     }
16 
17     @Override
18     public User findUserByUsernameAndPassword(User user) throws Exception {
19         return userDao.findUserByUsernameAndPassword(user);
20     }
21 
22     @Override
23     public String judgeUsername(User user) throws Exception {
24         String s = "";
25         userDao.findUserByUsername(user);
26         if(user.getUsername () == null || user.getUsername().equals("")){ //用户名为空
27             s = "null";
28         }else {
29 
30             try{
31                 //判断用户名是否重复
32                 User result = userDao.findUserByUsername(user);
33                 //如果不等于null则说明用户名重复
34                 if(result != null){
35                     s = "true" ;
36                 }else{
37                     //用户名不重复时
38                     s = "false";
39                 }
40             }catch (Exception e) {
41                 e.printStackTrace();
42             }
43         }
44         return s;
45     }
46 
47     @Override
48     public User findById(int id) throws Exception {
49         User user = userDao.findById(id);
50         return user;
51     }
52 }
复制代码

UserDaoImpl:

复制代码
  1 package dao.impl;
  2 
  3 import bean.User;
  4 import dao.UserDao;
  5 import java.sql.ResultSet;
  6 import java.sql.Connection;
  7 import java.sql.PreparedStatement;
  8 import java.text.SimpleDateFormat;
  9 import java.util.Date;
 10 import util.C3P0Util;
 11 
 12 /**
 13  * UserDao接口的实现
 14  */
 15 public class UserDaoImpl implements UserDao {
 16 
 17     @Override
 18     public void addUser(User user) throws Exception {
 19 
 20         String sql = "INSERT INTO t_user(username,password,email,realname,address,mobile,regTime)  VALUES(?,?,?,?,?,?,?)";
 21 
 22         try(
 23                 Connection conn = C3P0Util.getConnection();
 24                 PreparedStatement ps = conn.prepareStatement(sql);
 25         ) {
 26             ps.setString(1, user.getUsername());
 27             ps.setString(2, user.getPassword());
 28             ps.setString(3, user.getEmail());
 29             ps.setString(4, user.getRealname());
 30             ps.setString(5, user.getAddress());
 31             ps.setString(6, user.getMobile());
 32             //获取当前时间
 33             SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 34             Date nowTime = new Date();
 35             String strTime = sdf.format(nowTime);
 36             ps.setString(7, strTime);
 37 
 38             ps.executeUpdate();
 39         } catch (Exception e) {
 40             e.printStackTrace();
 41             throw new RuntimeException("添加失败!");
 42         }
 43 
 44 
 45     }
 46 
 47     @Override
 48     public User findUserByUsernameAndPassword(User user) throws Exception {
 49 
 50         String sql = "select * from t_user where username=? and password=?";
 51 
 52         User u = null;
 53 
 54         try(
 55                 Connection conn = C3P0Util.getConnection();
 56                 PreparedStatement ps = conn.prepareStatement(sql);
 57         ) {
 58             ps.setString(1, user.getUsername());
 59             ps.setString(2, user.getPassword());
 60             try(
 61                     ResultSet rs = ps.executeQuery();
 62             ){
 63                 if(rs.next()) {
 64                     u = new User();
 65 
 66                     u.setId(rs.getInt(1));
 67                     u.setUsername(rs.getString(2));
 68                     u.setPassword(rs.getString(3));
 69                     u.setEmail(rs.getString(4));
 70                     u.setRealname(rs.getString(5));
 71                     u.setAddress(rs.getString(6));
 72                     u.setMobile(rs.getString(7));
 73                     u.setRegTime(rs.getDate(8));
 74                     u.setRole(rs.getInt(9));
 75 
 76                 }
 77             }catch (Exception e){
 78             }
 79         } catch (Exception e) {
 80             e.printStackTrace();
 81         }
 82 
 83         return u;
 84     }
 85 
 86     @Override
 87     public User findUserByUsername(User user) throws Exception {
 88         String sql = "select username from t_user where username=?";
 89 
 90         User u = null;
 91 
 92         try(
 93                 Connection conn = C3P0Util.getConnection();
 94                 PreparedStatement ps = conn.prepareStatement(sql)
 95         ) {
 96 
 97             ps.setString(1, user.getUsername());
 98             try (
 99                     ResultSet rs = ps.executeQuery()
100             ) {
101                 //将查询出的结果数据封装到User对象中
102                 if(rs.next()){
103                     u = new User();
104                     u.setUsername(rs.getString("username"));
105                     return u;
106                 }
107             } catch (Exception e) {
108                 e.printStackTrace();
109             }
110         }catch (Exception e){
111             e.printStackTrace();
112         }
113         return u;
114     }
115 
116     @Override
117     public User findById(int id) throws Exception {
118         String sql = "select * from t_user where id=?";
119 
120         User u = null;
121 
122         try(
123                 Connection conn = C3P0Util.getConnection();
124                 PreparedStatement ps = conn.prepareStatement(sql)
125         ) {
126             ps.setInt(1, id);
127             try (
128                     ResultSet rs = ps.executeQuery()
129             ) {
130                 //将查询出的结果数据封装到Book对象中
131                 if(rs.next()){
132                     u = new User();
133 
134                     u.setId(rs.getInt(1));
135                     u.setUsername(rs.getString(2));
136                     u.setPassword(rs.getString(3));
137                     u.setEmail(rs.getString(4));
138                     u.setRealname(rs.getString(5));
139                     u.setAddress(rs.getString(6));
140                     u.setMobile(rs.getString(7));
141                     u.setRegTime(rs.getDate(8));
142                     u.setRole(rs.getInt(9));
143 
144                     return u;
145                 }
146             } catch (Exception e) {
147                 e.printStackTrace();
148             }
149         }catch (Exception e){
150             e.printStackTrace();
151         }
152         return u;
153     }
154 }
复制代码

 

回到顶部


前台书籍展示

index.html通过Ajax和Json技术从后台获取书籍信息:

复制代码
  1 <!DOCTYPE html>
  2 <html lang="en">
  3 <head>
  4     <meta charset="UTF-8">
  5     <title>书店</title>
  6     <style type="text/css">
  7         #main{
  8             width: 80%;height: auto;margin: 0 auto;overflow:auto;background: aliceblue;}
  9         #header_div{
 10             width:80%;height: auto;overflow:auto;margin:5px auto 5px;background: aliceblue;
 11             border-style: solid;border-color: darkgray;}
 12         #header{
 13             width:80%;height: auto;margin:0px auto ;padding: 20px;overflow:auto;}
 14         #book_div{
 15             width:80%;height: auto;margin:0px auto 50px auto;overflow:auto;border-style: solid;border-color: darkgray;background: aliceblue;}
 16         .childbook_div{
 17             width:80%;height: auto;margin:5px auto ;border-style: solid;border-color: darkgray;
 18             padding: 20px;overflow:auto;}
 19     </style>
 20 </head>
 21 <body>
 22     <div id="main">
 23         <div id="header_div">
 24             <div id="header">
 25                 <span style="font-family: 微软雅黑;font-size: xx-large">Lucky书店</span>
 26                 <br>
 27 
 28                 <p style="float: right">
 29                     <span id="loginT"><a href="login.html">登陆</a></span><span>&nbsp;&nbsp;</span>
 30                     <span id="registT"><a href="regist.html">注册</a> </span><span>&nbsp;&nbsp;</span>
 31                     <span id="shopCart"><a href="ShopCartServlet">购物车</a> </span><span>&nbsp;&nbsp;</span>
 32                     <span id="myOrder" style="display: none"><a href="myorder.html">我的订单</a></span>
 33                     <span id="admin" style="display: none"><a href="/AdminServlet?&id=back"><span>&nbsp;&nbsp;</span>Lucky工作台</a></span>
 34 
 35                 </p>
 36 
 37 
 38             </div>
 39 
 40         </div>
 41         <div id="book_div">
 42 
 43         </div>
 44     </div>
 45 </body>
 46 <script type="text/javascript" src="MyAjax.js"></script>
 47 <script type="text/javascript">
 48     window.onload = function () {
 49         var bookDiv = document.getElementById("book_div");
 50 
 51         //获取XMLHttpRequest对象
 52         var xhr = getXMLHttpRequest();
 53         var userId = "" ;
 54         //回调函数
 55         xhr.onreadystatechange = function(){
 56             if(xhr.readyState == 4){
 57                 if(xhr.status == 200){
 58                     var newsJ = xhr.responseText;//获取服务器返回的数据
 59 
 60                     //转化Json消息
 61                     var result = JSON.parse(newsJ);
 62 
 63                     if(result[0] != null){
 64                         //消息第一个元素为当前用户
 65                         var loginT = document.getElementById("loginT");
 66                         loginT.innerHTML = result[0].username;
 67                         userId = result[0].id;
 68                         var registT = document.getElementById("registT");
 69                         registT.innerHTML = "<a href='LogoutServlet'>注销</a>";
 70                         var shopCart = document.getElementById("shopCart");
 71                         shopCart.innerHTML = "<a href='ShopCartServlet?userId="+ userId +"'>购物车</a>";
 72                         var myOrder = document.getElementById("myOrder");
 73                         myOrder.style.display = "inline";
 74                         if(result[0].role == "1"){
 75                             var admin = document.getElementById("admin");
 76                             admin.style.display = "inline";
 77                         }
 78                     }
 79 
 80 
 81                     var childDivs = "";
 82                     //循环把书籍放入到div中
 83                     for(var i=1; i<result.length; i++){
 84                         childDivs += "<br><div class='childbook_div'>"
 85                                 + "<div style='float: left'>"
 86                                     + "<img src='" + result[i].imgAddress + "' width='198' height='198'/>"
 87                                 + "</div>"
 88                                 + "<div style='float: left'>"
 89                                     + "<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
 90                                     +"<sqan style='font-size: x-large;font-family: 黑体'>" + result[i].bookname + "</sqan>"
 91                                     + "<br><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
 92                                     + "在售价:" + result[i].sellingPrice
 93                                     + "<br><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
 94                                     + "<sqan>" +"描述:"+ result[i].depict +"</sqan>"
 95 
 96                                 + "</div>"
 97                                 + "<div style='float: left'>"
 98                                     + "<br><br><br><br><br><br><br><br>&nbsp;&nbsp;&nbsp;&nbsp;"
 99                                     + "<a href ='UpdateShopCartServlet?id=and&bookId=" + result[i].id + "&userId="
100                                         + userId + "&bookCount=1"+ "'>加入购物车</a>"
101                                 + "</div>"
102                             + "</div>";
103                     }
104 
105                     //把多个图书childDivs放入列表bookDiv中
106                     bookDiv.innerHTML = childDivs;
107 
108 
109                 }
110             }
111         }
112         //创建连接
113         xhr.open("get","/NewsServlet?id=book");
114         //发送请求
115         xhr.send(null);
116     }
117 </script>
118 </html>
复制代码

接受请求的servlet中用来传送书籍信息的代码:

复制代码
 1 PrintWriter out = response.getWriter();
 2 String id = request.getParameter("id");
 3 HttpSession session = request.getSession();
 4 if(id.equals("book")){//返回用户信息和findOnSaleBooks的集合
 5             BookService bs = new BookServiceImpl();
 6             try {
 7                 List bookList = bs.findOnSaleBooks();
 8                 Object userS = session.getAttribute("user");
 9                 //把集合中的数据转换为字符串返回到页面
10                 String newsJ = "";
11 
12                 List news = new ArrayList();
13                 news.add(userS);
14 
15                 for(int i = 0;i < bookList.size(); i++) {
16                     news.add(bookList.get(i));
17                 }
18 
19                 //使用json格式进行数据传输
20                 newsJ = JSONArray.toJSONString(news);
21                 //将数据响应到客户端
22                 response.getWriter().write(newsJ);
23 
24             } catch (Exception e) {
25                 e.printStackTrace();
26             }
27         }
复制代码


购物车模块

ShopCartServlet:

复制代码
 1 package servlet;
 2 
 3 import javax.servlet.ServletException;
 4 import javax.servlet.annotation.WebServlet;
 5 import javax.servlet.http.HttpServlet;
 6 import javax.servlet.http.HttpServletRequest;
 7 import javax.servlet.http.HttpServletResponse;
 8 import javax.servlet.http.HttpSession;
 9 import java.io.IOException;
10 
11 @WebServlet("/ShopCartServlet")
12 public class ShopCartServlet extends HttpServlet {
13     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
14         doGet(request, response);
15     }
16 
17     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
18 
19         HttpSession session = request.getSession();
20         Object user = session.getAttribute("user");
21 
22         if(user != null){
23             //用户登陆
24             response.sendRedirect("/shopCart.html");
25         }else if(user == null){
26             //未登录
27             response.getWriter().write("请先登录!!1秒后转到登陆界面");
28             response.setHeader("refresh", "1;url=" + request.getContextPath()
29                     + "/login.html");
30         }
31 
32     }
33 }

购物车相关操作UpdateShopCartServlet:

  1 package servlet;
  2 
  3 import bean.ShopCart;
  4 import org.apache.commons.beanutils.BeanUtils;
  5 import service.ShopCartService;
  6 import service.impl.ShopCartServiceImpl;
  7 
  8 import javax.servlet.ServletException;
  9 import javax.servlet.annotation.WebServlet;
 10 import javax.servlet.http.HttpServlet;
 11 import javax.servlet.http.HttpServletRequest;
 12 import javax.servlet.http.HttpServletResponse;
 13 import java.io.IOException;
 14 import java.lang.reflect.InvocationTargetException;
 15 
 16 @WebServlet("/UpdateShopCartServlet")
 17 public class UpdateShopCartServlet extends HttpServlet {
 18     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 19         doGet(request, response);
 20     }
 21 
 22     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 23         String id = request.getParameter("id");
 24         ShopCartService shopSvc = new ShopCartServiceImpl();
 25 
 26         if(id.equals("and")){
 27             //将表单提交的数据放在ShopCart类中
 28             ShopCart shopCart = new ShopCart();
 29             //使用commons-beanutils将表单数据封装到ShopCart对象中
 30             try {
 31                 BeanUtils.populate(shopCart, request.getParameterMap());
 32             } catch (IllegalAccessException e1) {
 33                 e1.printStackTrace();
 34             } catch (InvocationTargetException e1) {
 35                 e1.printStackTrace();
 36             }
 37 
 38             if(shopCart.getUserId() == 0){
 39                 response.getWriter().write("请先登陆!!1秒后跳转到登录页");
 40                 response.setHeader("refresh", "1;url=" + request.getContextPath()
 41                         + "/login.html");
 42             }else{
 43                 //调用业务逻辑
 44                 try {
 45                     shopSvc.addShopCart(shopCart);
 46                     //分发转向
 47                     response.getWriter().write("添加成功!1秒后转到购物车");
 48                     response.setHeader("refresh", "1;url=" + request.getContextPath()
 49                             + "/shopCart.html");
 50                 } catch (Exception e) {
 51                     e.printStackTrace();
 52                 }
 53             }
 54         }else if(id.equals("0")){
 55             //获取购物车ID
 56             String shopId = request.getParameter("shopId");
 57             //获取数量
 58             ShopCart shopCart = null;
 59             try {
 60                 shopCart = shopSvc.findById(shopId);
 61             } catch (Exception e) {
 62                 e.printStackTrace();
 63             }
 64             int count = shopCart.getBookCount();
 65             if(count > 1){
 66                 //如果数量大于1,就减1
 67                 try {
 68                     shopSvc.subCount(count,shopId);
 69                 } catch (Exception e) {
 70                     e.printStackTrace();
 71                 }
 72                 response.sendRedirect("shopCart.html");
 73             }
 74         } else if(id.equals("1")){
 75             //获取购物车ID
 76             String shopId = request.getParameter("shopId");
 77             //获取数量
 78             ShopCart shopCart = null;
 79             try {
 80                 shopCart = shopSvc.findById(shopId);
 81             } catch (Exception e) {
 82                 e.printStackTrace();
 83             }
 84             int count = shopCart.getBookCount();
 85             try {
 86                 shopSvc.addCount(count,shopId);
 87             } catch (Exception e) {
 88                 e.printStackTrace();
 89             }
 90             response.sendRedirect("shopCart.html");
 91         }else if(id.equals("remove")){
 92             //获取checkbox的值
 93             String[] shopCartList = request.getParameterValues("shopCart");
 94             //如果提交为空
 95             if(shopCartList == null){
 96                 response.getWriter().write("未选择书籍!!1秒后返回");
 97                 response.setHeader("refresh", "1;url=" + request.getContextPath()
 98                         + "/shopCart.html");
 99             }
100 
101             shopSvc.removeShopCart(shopCartList);
102 
103             response.sendRedirect("shopCart.html");
104         }
105     }
106 }
 

向html发送用户购物车信息的servlet中的相关代码:

 1 PrintWriter out = response.getWriter();
 2 String id = request.getParameter("id");
 3 HttpSession session = request.getSession();
 4 if(id.equals("shop")){ //返回用户和购物车信息
 5             User user = (User)session.getAttribute("user");
 6             List<ShopCart> shopCartList = new ArrayList<>();
 7             if(user != null){
 8                 //用户登陆
 9                 //获取该用户购物车List
10                 ShopCartService shopCartService = new ShopCartServiceImpl();
11                 try {
12                     shopCartList = shopCartService.findByUserId(String.valueOf(user.getId()));
13                 } catch (Exception e) {
14                     e.printStackTrace();
15                 }
16                 //获取用户session
17                 Object userS = session.getAttribute("user");
18                 //将session和购物车打包
19                 List news = new ArrayList();
20                 news.add(userS);
21                 if(shopCartList!=null){
22                     for(int i = 0;i < shopCartList.size(); i++) {
23                         news.add(shopCartList.get(i));
24                     }
25                 }
26 
27                 //使用json格式进行数据传输
28                 String newsJ = "";
29                 newsJ = JSONArray.toJSONString(news);
30                 //将数据响应到客户端
31                 response.getWriter().write(newsJ);
32 
33 
34             }else if(user == null){
35                 //未登录
36                 //获取用户session
37                 Object userS = session.getAttribute("user");
38                 List news = new ArrayList();
39                 news.add(userS);
40                 //使用json格式进行数据传输
41                 String newsJ = "";
42                 newsJ = JSONArray.toJSONString(news);
43                 //将数据响应到客户端
44                 response.getWriter().write(newsJ);
45             }
46 
47         }
 

推荐阅读