實習就要結束了,最終要上交的是網上書城項目和一份文檔。接下來簡要介紹一下項目。 項目是根據三層架構來寫,數據訪問層(DAO層)、系統業務邏輯控制處理層(servlet層)、和界面層(jsp)。 首先在DAO層構造好SQL語句,對資料庫進行操作,在servlet層調用Dao層相關方法進行相應的邏輯處理 ...
實習就要結束了,最終要上交的是網上書城項目和一份文檔。接下來簡要介紹一下項目。
項目是根據三層架構來寫,數據訪問層(DAO層)、系統業務邏輯控制處理層(servlet層)、和界面層(jsp)。
首先在DAO層構造好SQL語句,對資料庫進行操作,在servlet層調用Dao層相關方法進行相應的邏輯處理,JSP負責構造界面以及顯示數據。
下麵貼出代碼,僅供參考,一些功能的具體實現在功能說明時有所介紹,只貼一些比較重要的部分的代碼,大家主要重在理解。
此次項目,我感覺比較困難的部分是 加入購物車 部分和訂單處理這部分。
加入購物車部分,一定要對集合操作非常熟悉才可以比較好的處理,另外還有合理的採用session,另外比較好的是構造一個BookShopping實體來幫助我們處理購物車部分的計算價格問題;
訂單處理部分,生成訂單,就是根據購物車裡的有關書的一些信息,將這些信息插入order表中,會自動生成一個訂單編號,因為當前購物車訂單號相同;
生成訂單,由book表、order表拼湊成items表;
生成歷史訂單,是根據當前登錄用戶在Order表中查找到此用戶所有的訂單號,再根據訂單號在items表中查到所有的訂單詳情。
註冊功能
package com.mm.Dao.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.mm.Dao.UserDao; import com.mm.Utils.JDBCUtils; import com.mm.bean.User; //Dao層 資料庫介面層 public class UserDaoImpl implements UserDao { public boolean addUser(User user) { // TODO Auto-generated method stub Connection con = null; PreparedStatement ps = null; ResultSet rs = null; try { String sql = "insert into user values(?,?,?,?)"; con = JDBCUtils.getconnection(); ps = con.prepareStatement(sql); ps.setString(1, user.getUsername()); ps.setString(2, user.getPassword()); ps.setString(3, user.getEmail()); ps.setString(4, user.getAddress()); int count = ps.executeUpdate(); System.out.print("受影響的行數是:"+count); return true; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ JDBCUtils.release(rs, ps, con); } return false; } public User findUser(String name, String password) { // TODO Auto-generated method stub Connection con = null; PreparedStatement ps = null; ResultSet rs = null; User user = new User(); String sql = "select * from user where username = ? and password = ?"; try { con = JDBCUtils.getconnection(); ps = con.prepareStatement(sql); ps.setString(1, name); ps.setString(2, password); rs = ps.executeQuery(); while(rs.next()){ try { user.setUsername(rs.getString("username")); user.setPassword(rs.getString("password")); user.setEmail(rs.getString("email")); user.setAddress(rs.getString("address")); return user; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ JDBCUtils.release(rs, ps, con); } } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ JDBCUtils.release(rs, ps, con); } return null; } }
1
//這層可以不要,將它歸併到servlet里。
package com.mm.service.impl; 2 3 import com.mm.Dao.UserDao; 4 import com.mm.Dao.impl.UserDaoImpl; 5 import com.mm.bean.User; 6 import com.mm.service.UserService; 7 8 public class UserServiceImpl implements UserService { 9 10 public User login(String username, String password) { 11 // TODO Auto-generated method stub 12 UserDao dao = new UserDaoImpl(); 13 User user = dao.findUser(username, password); 14 return user; 15 } 16 17 public boolean register(User user) { 18 // TODO Auto-generated method stub 19 UserDao dao = new UserDaoImpl(); 20 if(dao.addUser(user)){ 21 return true; 22 } 23 return false; 24 25 } 26 27 }
1 package com.mm.servlet; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 import java.util.HashMap; 6 import java.util.Map; 7 8 import javax.servlet.ServletException; 9 import javax.servlet.http.HttpServlet; 10 import javax.servlet.http.HttpServletRequest; 11 import javax.servlet.http.HttpServletResponse; 12 13 import com.mm.Dao.UserDao; 14 import com.mm.Dao.impl.UserDaoImpl; 15 import com.mm.bean.User; 16 import com.mm.service.UserService; 17 import com.mm.service.impl.UserServiceImpl; 18 19 20 21 public class RegisterServlet extends HttpServlet { 22 23 public void doGet(HttpServletRequest request, HttpServletResponse response) 24 throws ServletException, IOException { 25 doPost(request,response); 26 27 } 28 29 30 Map<String, String> errors = new HashMap<String, String>(); 31 public void doPost(HttpServletRequest request, HttpServletResponse response) 32 throws ServletException, IOException { 33 //獲取參數值 34 String username = request.getParameter("username"); 35 String password = request.getParameter("password"); 36 String repassword = request.getParameter("repassword"); 37 String email = request.getParameter("email"); 38 String address = request.getParameter("address"); 39 40 //組裝成一個user對象 41 User user = new User(); 42 user.setUsername(username); 43 user.setPassword(password); 44 user.setEmail(email); 45 user.setAddress(address); 46 //調用dao 來註冊 47 UserService dao = new UserServiceImpl(); 48 boolean re = dao.register(user); 49 50 //根據註冊結果來跳轉 51 if(re){ 52 request.getRequestDispatcher("register_success.jsp").forward(request, response); 53 } 54 55 }else{ 56 request.setAttribute("errors", errors); 57 request.getRequestDispatcher("register.jsp").forward(request, response); 58 } 59 60 } 65 } 66 67 68
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 5 Map<String,String> errors = (HashMap<String,String>)request.getAttribute("errors"); 6 %> 7 8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 9 <html> 10 <head> 11 <base href="<%=basePath%>"> 12 13 <title>註冊頁面</title> 14 15 <link type="text/css" rel="stylesheet" href="css/style.css" /> 16 <script type="text/javascript" src="jquery.js"></script> 17 18 <script type="text/javascript"> 19 function validate(){ 20 var username = document.getElementById("user1").value; 21 var password = document.getElementById("pwd1").value; 22 var repassword = document.getElementById("rpwd1").value; 23 var email = document.getElementById("email1").value; 24 var address = document.getElementById("address1").value; 25 var reg1 = /[a-zA-Z]\w*/; 26 var reg2 = /\w+([-+.']\w+)*@\w+([-.]\w+)*.\w+([-.]\w+)*/; 27 if(username.length<=0) alert("用戶名不能為空!"); 28 else if(!reg1.test(username)) alert("用戶名格式不正確!"); 29 else if(password.length<6) alert("密碼長度必須大於等於6"); 30 else if(password!=repassword) alert("兩次密碼不一致!"); 31 else if(!reg2.test(email)) alert("郵箱格式不正確!!"); 32 else document.form[1].submit(); 33 } 34 </script> 35 36 </head> 37 38 <body style="text-align:center"> 39 <div id="header" class="wrap"> 40 <div id="logo">北大青鳥網上書城</div> 41 <div id="navbar"> 42 <form method="get" name="search" action=""> 43 搜索:<input class="input-text" type="text" name="keywords" /><input class="input-btn" type="submit" name="submit" value="" /> 44 </form> 45 </div> 46 </div> 47 <div id="register"> 48 <div class="title"> 49 <h2>歡迎註冊北大青鳥網上書城</h2> 50 </div> 51 <div class="steps"> 52 <ul class="clearfix"> 53 <li class="current">1.填寫註冊信息</li> 54 <li class="unpass">2.註冊成功</li> 55 </ul> 56 </div> 57 <form method="post" action="RegisterServlet" id="registerForm"> 58 <dl> 59 <dt>用 戶 名:</dt> 60 <dd><input id = "user1" class="input-text" type="text" name="username" /><span>${errors.username }</span></dd> 61 <dt>密 碼:</dt> 62 <dd><input id = "pwd1" class="input-text" type="password" name="password" /><span>${errors.password}</span></dd> 63 <dt>確認密碼:</dt> 64 <dd><input id = "rpwd1" class="input-text" type="password" name="repassword" /><span>${errors.repassword }</span></dd> 65 <dt>Email地址:</dt> 66 <dd><input id = "email1" class="input-text" type="text" name="email" /><span>${errors.email }</span></dd> 67 <dt>通信地址:</dt> 68 <dd><input id = "address1" class="input-text" type="text" name="address" /></dd> 69 <dt></dt> 70 <dd class="button"><input class="input-reg" type="submit" name="register" onClick="validate()"/></dd> 71 </dl> 72 </form> 73 </div> 74 <div id="footer" class="wrap"> 75 北大青鳥網上書城 © 版權所有 76 77 </div> 78 </body> 79 </html>
登錄功能
登錄功能用到cookie會話技術,可以回顯用戶名密碼;前提是覆選框要選中
1 package com.mm.servlet; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 6 import javax.mail.Session; 7 import javax.servlet.ServletException; 8 import javax.servlet.http.Cookie; 9 import javax.servlet.http.HttpServlet; 10 import javax.servlet.http.HttpServletRequest; 11 import javax.servlet.http.HttpServletResponse; 12 import javax.servlet.http.HttpSession; 13 14 import com.mm.bean.User; 15 import com.mm.service.UserService; 16 import com.mm.service.impl.UserServiceImpl; 17 18 public class LoginServlet extends HttpServlet { 19 20 21 public void doGet(HttpServletRequest request, HttpServletResponse response) 22 throws ServletException, IOException { 23 //得到頁面輸入的用戶名和密碼 24 String username = request.getParameter("username"); 25 String password = request.getParameter("password"); 26 String remember = request.getParameter("remember"); 27 //從資料庫中查找是否存在 28 UserService us = new UserServiceImpl(); 29 User user = us.login(username, password); 30 //找到 顯示登陸成功,跳轉到 User主頁,跳轉不成功,在login.jsp 31 //user不為空說明此用戶真實存在 32 if(user != null){ 33 //如果用戶找到了,那就說明是合法用戶 34 //把用戶放入cookies中 35 Cookie cookie = new Cookie("username",username); 36 Cookie cookie1 = new Cookie("password",password); 37 if("on".equals(remember)){ 38 cookie.setMaxAge(300); 39 cookie1.setMaxAge(300); 40 }else{ 41 cookie.setMaxAge(0); 42 cookie1.setMaxAge(0); 43 } 44 45 response.addCookie(cookie); 46 response.addCookie(cookie1); 47 48 //此用戶存到session中 49 request.getSession().setAttribute("username", username); 50 51 52 response.setHeader("refresh", "3;url=BookServlet?op=list"); 53 54 }else{//非法用戶 55 request.setAttribute("error", "用戶名或密碼錯誤"); 56 57 request.getRequestDispatcher("login.jsp").forward(request, response); 58 59 60 } 61 62 63 } 64 65 66 public void doPost(HttpServletRequest request, HttpServletResponse response) 67 throws ServletException, IOException { 68 doGet(request,response); 69 70 } 71 72 }
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>登錄界面</title> <link type="text/css" rel="stylesheet" href="css/style.css" /> </head> <body style="text-align:center"> <div id="header" class="wrap"> <div id="logo">北大青鳥網上書城</div> <div id="navbar"> <form method="get" name="search" action=""> 搜索:<input class="input-text" type="text" name="keywords" /> <input class="input-btn" type="submit" name="submit" value="" /> </form> </div> </div> <div id="login"> <% //拿到錯誤信息 String name = (String) request.getAttribute("error") ; if(name != null) out.write("<font color = red>" + name + "</font>") ; String username = "" ; String password = "" ; //拿到客戶端攜帶的所有的Cookie Cookie[] cs = request.getCookies() ; //迴圈判斷,如果拿到cookies for (int i = 0; cs !=null && i < cs.length; i++) { Cookie c = cs[i] ; if(c.getName().equals("username")){ //說明找到了存儲用戶名的cookie username = c.getValue() ; } if(c.getName().equals("password")){ //說明找到了存儲密碼的Cookie password = c.getValue() ; } } %> <h2>用戶登陸</h2> <form method="post" action="LoginServlet"> <dl> <dt>用戶名: </dt> <dd><input class="input-text" type="text" name="username" value = "<%=username %>"/><span>${error}</span></dd> <dt>密 碼: </dt> <dd><input class="input-text" type="password" name="password" value = "<%=password%>"/></dd> <dt><input class = "input-text" type= "checkbox" name = "remember" value = "on"/></dt> <dd>是否記住此用戶</dd> <dt></dt> <dd class="button"><input class="input-btn" type="submit" name="submit" value="" /> <input class="input-reg" type="button" name="register" value="" onclick="window.location='register.jsp';" /></dd> </dl> </form> </div> <div id="footer" class="wrap"> 北大青鳥網上書城 © 版權所有 </div> </body> </html>
註銷功能
登錄時將此用戶存入session中,方便後邊的使用;註銷時將此用戶從session中刪除即可。
1 HttpSession se = request.getSession(false); 2 if(se==null) { 3 response.sendRedirect("login.jsp"); 4 return ; 5 } 6 7 se.removeAttribute("username"); 8 response.sendRedirect("login.jsp");
加入購物車功能
方便對購物車進行管理,創建了一個購物車的實體,計算出了每種書花費的價格
1 package com.mm.bean; 2 3 public class BookShopping { 4 private Book book; 5 private int count;//購買的數量 6 private double totalprice;//總價格 7 public BookShopping(Book book , int count) { 8 this.book = book; 9 this.count = count; 10 this.totalprice = this.book.getBookprice()*this.count; 11 } 12 public Book getBook() { 13 return book; 14 } 15 public void setBook(Book book) { 16 this.book = book; 17 } 18 19 public int getCount() { 20 return count; 21 } 22 public void setCount(int count) { 23 this.count = count; 24 } 25 public double getTotalprice() { 26 return totalprice; 27 } 28 public void setTotalprice(double totalprice) { 29 this.totalprice = totalprice; 30 } 31 32 33 }BookShopping實體類
1 package com.mm.servlet; 2 3 import java.io.IOException; 4 import java.util.HashMap; 5 import java.util.List; 6 import java.util.Map; 7 import java.util.Set; 8 9 import javax.servlet.ServletException; 10 import javax.servlet.http.HttpServlet; 11 import javax.servlet.http.HttpServletRequest; 12 import javax.servlet.http.HttpServletResponse; 13 import javax.servlet.http.HttpSession; 14 15 import com.mm.Dao.impl.BookDaoImpl; 16 import com.mm.bean.Book; 17 18 public class AddCartServlet extends HttpServlet { 19 20 21 public void doGet(HttpServletRequest request, HttpServletResponse response) 22 throws ServletException, IOException { 23 doPost(request,response); 24 } 25 26 //將從User首頁選中的加入購物車,還要根據書的本數還要計算價格 27 public void doPost(HttpServletRequest request, HttpServletResponse response) 28 throws ServletException, IOException { 29 //從界面拿到選中的即需要加入購物車的所有圖書的Id號 30 String[] bookIds =(String[])request.getParameterValues("bookid"); 31 Map<String,Integer> bookMap = (Map<String, Integer>) request.getSession().getAttribute("bookMap"); 32 if(bookMap==null) bookMap = new HashMap(); 33 //遍歷選擇的商品 34 if(bookIds!=null&&bookIds.length>0){ 35 for(String bookId: bookIds){ 36 //添加到購物車 37 Integer count = bookMap.get(bookId);//得到bookid對應的數量 38 if(count==null) bookMap.put(bookId, 1); 39 else{ 40 bookMap.put(bookId, count+1); 41 } 42 } 43 } 44 45 //將購物車裡書的id及選購的本數放入sesssion中, request.getSession().setAttribute("bookMap",bookMap); 46 47 request.getRequestDispatcher("goon.jsp").forward(request, response); 48 } 49 50 }加入購物車的servlet
1 <%@ page language="java" import="java.util.*,com.mm.bean.*,com.mm.Dao.*,com.mm.Dao.impl.*" pageEncoding="UTF-8"%> 2 <%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core"%> 3 <% 4 String path = request.getContextPath(); 5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 6 7 Map<String,Integer> bookMap =(Map<String,Integer>)request.getSession().getAttribute("bookMap"); 8 BookDao dao = new BookDaoImpl(); 9 Iterator keys = bookMap.keySet().iterator(); 10 double hj = 0; 11 List<BookShopping> list = new ArrayList(); 12 while(keys.hasNext()){ 13 String key = (String)keys.next();//book的id 14 Book book = dao.findbookById(Integer.parseInt(key)); 15 int count = bookMap.get(key); 16 BookShopping bs = new BookShopping(book,count);//bookshopping里的構造函數,把價格算出來了。 17 hj+=bs.getTotalprice();//算總的合計,累計疊加 18 list.add(bs); 19 } 20 21 request.getSession().setAttribute("bookshoppinglist",list); 22 23 24 String username = (String)request.getSession().getAttribute("username"); 25 26 %> 27 28 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 29 <html> 30 <head> 31 <base href="<%=basePath%>"> 32 33 <title>購物車界面</title> 34 <link type="text/css" rel="stylesheet" href="css/style.css" /> 35 <script type="text/javascript" src = "jquery.js"></script> 36 <script type="text/javascript"> 37 </script> 38 39 </head> 40 41 <body style="text-align:center"> 42 <div id="header" class="wrap"> 43 <div id="logo">北大青鳥網上書城</div> 44 <div id="navbar"> 45 <div class="userMenu"> 46 <ul> 47 <li><a href="showbook.jsp">歡迎您:${username }</a></li> 48 <li><a href="orderlist.jsp">我的訂單</a></li> 49 <li class="current"><a href="shopping.jsp">購物車</a></li> 50 <li><a href="exit.jsp">註銷</a></li> 51 </ul> 52 </div> 53 <form method="get" name="search" action=""> 54 搜索:<input class="input-text" type="text" name="keywords" /><input class="input-btn" type="submit" name="submit" value="" /> 55 </form> 56 </div> 57 </div> 58 <div id="content" class="wrap"> 59 <div class="list bookList"> 60 <form method="post" name="shoping" action="OrderServlet?op=list"> 61 <table> 62 <tr class="title"> 63 <th class="view">圖片預覽</th> 64 <th>庫存</th> 65 <th>書名</th> 66 <th class="nums">數量</th> 67 <th class="nums">單價</th> 68 <th class="price">總價</th> 69 70 </tr> 71 72 <c:forEach var="obj" items = "${bookshoppinglist}"> 73 <tr> 74 <td>${obj.book.bookimg}</td> 75 <td>${obj.book.booksave}</td> 76 <td>${obj.book.bookname}</td> 77 <td>${obj.count }</td> 78 <td>${obj.book.bookprice }</td> 79