java EE 網上書店 —— 核心代碼實現

介紹

  項目採用B/S架構、MVC開發模式,使用java語言,根據Java EE 標準開發,旨在感覺java web項目開發流程、學習與理解java EE基礎技術和原理。javascript

M: Model模型 JavaBean
V:view視圖 Html
C:Controller控制器 Servlet
css

其中Html與Servlet之間用Ajax與Json技術互動。html


 項目結構

使用maven構建,分爲Dao、Service、Servlet、和前端展現層前端

 


數據持久化工具

使用C3p0數據庫鏈接池java

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

複製代碼
<?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:web

複製代碼
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:sql

複製代碼
 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:apache

複製代碼
 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 }
相關文章
相關標籤/搜索