基於Servlet&Jsp的網上書店設計(三)

六,本設計Servlet&Jsp代碼實現過程

用一句話概括,用戶在客戶端請求jsp頁面,jsp頁面將結果提交到Servlet,由Servlet負責處理結果,訪問數據庫等操作,並將參數結果放在request,session,application等元素中,然後通過請求轉發和重定向轉發到其他jsp頁面或者Servlet

6.1進入主頁和查看書籍詳細信息功能

客戶通過客戶端請求地址http://localhost:8080/ShoppingCart/frame.jsp,請求主頁面,主頁面採用框架標籤frameset,框架中頁面再轉發請求Http://localhost:8080/ShoppingCart/PageQueryServlet,  返回的books.jsp頁面

frame.Jsp的代碼

[html]  view plain  copy
 print ?
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2.   
  3. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  4. <html>  
  5.   <head>  
  6.     <title>喵喵網上書店</title>     
  7.   </head>    
  8.    
  9.    <frameset cols="25%,75%" frameborder="NO" border="0" framespacing="0">  
  10.        <frame src="login.jsp" noresize scrolling="no" name="leftframe">       
  11.        <frame src="Http://localhost:8080/ShoppingCart/PageQueryServlet" name="rightframe" noresize scrolling="yes">       
  12.    </frameset>  
  13. </html>  

PageQueryServlet.Java的Servlet是分頁顯示書籍的代碼

[java]  view plain  copy
 print ?
  1. package com.servlets;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.PrintWriter;  
  5. import java.util.List;  
  6.   
  7. import javax.servlet.ServletException;  
  8. import javax.servlet.http.HttpServlet;  
  9. import javax.servlet.http.HttpServletRequest;  
  10. import javax.servlet.http.HttpServletResponse;  
  11. import com.Dao.PageQueryDao;  
  12. import com.beans.Book;  
  13.   
  14. public class PageQueryServlet extends HttpServlet {  
  15.   
  16.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  17.             throws ServletException, IOException {  
  18.           int currpage=1;  
  19.           if(request.getParameter("page")!=null){  
  20.               currpage=Integer.parseInt(request.getParameter("page"));  
  21.           }  
  22.           
  23.          PageQueryDao pagedao=new PageQueryDao();  
  24.          List<Book> list=pagedao.getPageList(currpage);//查詢當前頁記錄  
  25.          request.setAttribute("list", list);   
  26.          int pages;   //計算查詢總頁數  
  27.          int count=pagedao.FindCounts();  
  28.          if(count%Book.PAGE_SIZE==0){  
  29.              pages=count/Book.PAGE_SIZE;  
  30.          }  
  31.          else{  
  32.              pages=count/Book.PAGE_SIZE+1;  
  33.          }  
  34.            
  35.          StringBuffer sb=new StringBuffer();  
  36.          //構建分頁條  
  37.          for(int i=1;i<=pages;i++){  
  38.              if(i==currpage){  
  39.                  sb.append("『" + i + "』");  
  40.              }  
  41.              else{  
  42.                  sb.append("<a href='PageQueryServlet?page="+i+"'>"+i+"</a>");  
  43.              }  
  44.              sb.append(" ");  
  45.          }  
  46.          request.setAttribute("bar", sb.toString());  
  47.          request.getRequestDispatcher("books.jsp").forward(request, response);  //請求轉發    
  48.     }  
  49.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  50.         doGet(request, response);  
  51.     }  
  52.   
  53. }  

Books.jsp是顯示書籍

[html]  view plain  copy
 print ?
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%@page import="java.util.List"%>  
  3. <%@page import="com.beans.Book"%><html>  
  4. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  5. <html>  
  6.   <head>  
  7.     <title>圖書信息列表</title>  
  8.   
  9.     <!-- 
  10.     <link rel="stylesheet" type="text/css" href="styles.css"> 
  11.     -->  
  12.     <style type="text/css">  
  13.         a:link{color:#FF4500;text-decoration:none}/*未訪問,紅色,無下劃線*/  
  14.         a:active{color:blue;}/*激活,紅色*/  
  15.         a:visited{color:red;text-decoration:none}/*已訪問,紫色,無下劃線*/  
  16.         a:hover{color:yellow;text-decoration:underline}/*鼠標移動上面,藍色,下劃線*/  
  17.     </style>  
  18.   </head>  
  19.     
  20.   <body bgcolor="#98FB98" >  
  21.         <br><br>  
  22.        <table align="center" width="900">  
  23.           <tr>  
  24.              <td align="center" colspan="6" valign="baseline">  
  25.                  <h2 style=" font-family:隸書;color:#0A0A0A;font-size:50px">喵喵網上書店</h2>  
  26.              </td>  
  27.           </tr>  
  28.             <%! int i=1,j=1; %>  
  29.            <% List<Book> list=(List<Book>)request.getAttribute("list");%>  
  30.            <% for(j=1;j<=2;j++){ %>  
  31.              <tr >  
  32.             <%   
  33.                for(Book b:list){   
  34.                    if(j==2){  
  35.                      if(b.getBookId()<=3||(b.getBookId()>=7&&b.getBookId()<=9)) continue;  
  36.                    }                           
  37.              %>           
  38.             <td width="100" height="140"><img src="images/<%=String.valueOf(b.getBookId()-1) %>.jpg"/></td>  
  39.             <td width="160">   
  40.                  <font color="#0000FF" face="隸書">ISDN :<%=b.getBookId() %></font><br>  
  41.                  <font color="#0000FF" face="隸書"> 書 名:<%=b.getName() %></font><br>  
  42.                  <font color="#0000FF" face="隸書"> 作 者:<%=b.getAuthor() %></font><br>  
  43.                  <font color="#0000FF" face="隸書">出 版:<%=b.getPublisher() %></font><br>  
  44.                  <font color="#0000FF" face="隸書">價 格:<%=b.getPrice() %> </font><br>     
  45.                     <a href="BookInfo/<%=b.getBookId()%>.jsp?bookid=<%=b.getBookId()%>">查看詳細信息</a>                             
  46.             </td>   
  47.                <% if(b.getBookId()%3==0) break; %>                           
  48.           <%} %>     
  49.           </tr>  
  50.           <%} %>           
  51.           <tr>  
  52.             <td align="right" colspan="6"><%= request.getAttribute("bar") %></td>            
  53.           </tr>  
  54.        </table>  
  55.   </body>  
  56. </html>  
結果圖:



點擊「查看詳細信息」會把該書的bookId放入request中,然後跳轉到相應的書的詳細信息頁:

Id=1的書的代碼,1.jsp

[html]  view plain  copy
 print ?
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%@ page import="com.Dao.BookDao" %>  
  3. <%@ page import="com.beans.Book" %>  
  4. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  5. <html>  
  6.   <head>  
  7.     <title>三國演義</title>  
  8.     <!-- 
  9.     <link rel="stylesheet" type="text/css" href="styles.css"> 
  10.     -->  
  11.     <style type="text/css">  
  12.         a:link{color:blue;text-decoration:none}/*未訪問,紅色,無下劃線*/  
  13.         a:active{color:blue;}/*激活,紅色*/  
  14.         a:visited{color:yellow;text-decoration:none}/*已訪問,紫色,無下劃線*/  
  15.         a:hover{color:blue;text-decoration:underline}/*鼠標移動上面,藍色,下劃線*/  
  16.     </style>  
  17.   
  18.   </head>   
  19.   <body  bgcolor="#98FB98" >  
  20.         <% int bookid=Integer.parseInt(request.getParameter("bookid"));    
  21.             BookDao bookdao=new BookDao();     
  22.             Book b=bookdao.getBookById(bookid);    
  23.             String msg=(String)request.getAttribute("msg");                     
  24.          %>  
  25.          
  26.         <br><br><br><br>  
  27.       <form action="http://localhost:8080/ShoppingCart/CheckLogin?bookid=<%=b.getBookId() %>" method="post" name="checkform">  
  28.         <table align="center"  width="800">  
  29.              <tr>  
  30.                 <td width="100" height="140"><img src="Http://localhost:8080/ShoppingCart/images/<%=String.valueOf(b.getBookId()-1) %>.jpg"/></td>  
  31.                 <td >   
  32.                   <font color="#000000" face="隸書" size="4">ISDN :<%=b.getBookId() %></font><br>  
  33.                   <font color="#000000" face="隸書" size="4"> 書 名:<%=b.getName() %></font><br>  
  34.                   <font color="#000000" face="隸書" size="4"> 作 者:<%=b.getAuthor() %></font><br>  
  35.                   <font color="#000000" face="隸書" size="4">出 版:<%=b.getPublisher() %></font><br>  
  36.                   <font color="#000000" face="隸書" size="4">價 格:<%=b.getPrice() %> </font><br>                                             
  37.                 </td>   
  38.              </tr>  
  39.              <tr><td colspan="2"> <hr color="#FF0000"></td></tr>    
  40.                
  41.              <tr>  
  42.                <td colspan="2"> <h2><font color="#8B0000" face="隸書">簡介:</font></h2></td>  
  43.              </tr>    
  44.                
  45.              <tr>  
  46.                <td colspan="2">    
  47.                <p style="font-family:'楷體'">      《三國演義》是中國第一部長篇章回體歷史演義小說,以描寫東漢末年的戰爭爲主,反映了魏、蜀、吳三個政治集團之間的政治和軍事鬥爭。分爲黃巾之亂、董卓之亂、三國鼎立三大部分。在廣闊的背景上,上演了一幕幕氣勢磅礴的戰爭場面。</p>  
  48.                <p style="font-family:'楷體'">      羅貫中將兵法三十六計融於字裏行間,既有情節,也有兵法韜略。本書反映了豐富的歷史內容,人物名稱、地理名稱、主要事件和人物性格與《三國志》基本相同,是在固定形象基礎上,進行再發揮,這也是歷史演義小說的套路。本書一方面反映了真實的三國曆史,照顧到讀者希望瞭解真實歷史的需要;另一方面,根據明朝社會的實際情況對三國人物進行了誇張、美化、醜化等等。</p></td>  
  49.              </tr>  
  50.                  
  51.               <tr>  
  52.                 <td colspan="2" align="right">                  
  53.                 <input value="加入購物車" type="submit">  <a href="Http://localhost:8080/ShoppingCart/PageQueryServlet">繼續購物</a></td>  
  54.                </tr>           
  55.         </table>                
  56.      </form>  
  57.        <% if(msg!=null){ %>  
  58.               <%=msg %>  
  59.          <%} %>  
  60.   </body>  
  61. </html>  

結果圖:

在該頁面中點擊「加入購物車」,請求會提交到CheckLogin的Servlet,在該Servlet中完成檢查用戶有無登錄的操作和將書加入到該用戶的購物車的操作。如果用戶爲登錄會「用戶爲登錄」窗口提示信息,如果登錄了,就成功加入了該用戶的購物車,感覺淘寶的模式有點像,點擊該用戶的「查看我的購物車」即可看到剛加的書籍。若購物車中有書籍會提示「此書已加入購物車,請勿重複添加!」,只需在購物車中調整購買數量即可。

CheckLogin.java

[java]  view plain  copy
 print ?
  1. package com.servlets;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.PrintWriter;  
  5.   
  6. import javax.servlet.ServletException;  
  7. import javax.servlet.http.HttpServlet;  
  8. import javax.servlet.http.HttpServletRequest;  
  9. import javax.servlet.http.HttpServletResponse;  
  10. import javax.servlet.http.HttpSession;  
  11.   
  12. import com.Dao.BookDao;  
  13. import com.Dao.CartDao;  
  14. import com.beans.Book;  
  15.   
  16. public class CheckLogin extends HttpServlet {  
  17.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  18.             throws ServletException, IOException {  
  19.         response.setCharacterEncoding("gb2312");  
  20.         HttpSession session=request.getSession();   
  21.         //String user=(String) session.getAttribute("user");//從session中獲取用戶  
  22.           
  23.         System.out.println("加入購物車");  
  24.         String bookid=request.getParameter("bookid");  
  25.         BookDao bookdao=new BookDao();  
  26.         Book b=bookdao.getBookById(Integer.parseInt(bookid));//通過傳過來的bookid返回書的對象  
  27.           
  28.         System.out.println("以獲取用戶");  
  29.         if( session.getAttribute("userid")==null){//如果用戶未登錄  
  30.             System.out.println("用戶未空");  
  31.             request.setAttribute("msg""<script language='javascript'>window.alert('用戶未登錄!');</script>");  
  32.             request.getRequestDispatcher("BookInfo/"+b.getBookId()+".jsp").forward(request, response);  
  33.         }  
  34.         else{  
  35.             //加入購物車的操作            
  36.             CartDao cartdao=new CartDao();  
  37.             String userid=(String)session.getAttribute("userid");  
  38.             //System.out.println(b.getName());  
  39.             //System.out.println((String)session.getAttribute("userid"));     
  40.             boolean cc=cartdao.isContainBook(userid, bookid);  
  41.             if(cc){//如果此書已添加  
  42.                 request.setAttribute("msg""<script language='javascript'>window.alert('此書已加入購物車,請勿重複添加!');</script>");  
  43.                 request.getRequestDispatcher("BookInfo/"+b.getBookId()+".jsp").forward(request, response);  
  44.             }else{//如果此書沒添加  
  45.                   
  46.                 boolean bb=cartdao.InsertBook((String)session.getAttribute("userid"), b);  
  47.                 if(bb){//如果插入書籍成功  
  48.                     /*PrintWriter out=response.getWriter(); 
  49.                     out.print("<script language='javascript'>window.alert('成功加入購物車!');</script>");               
  50.                     out.flush(); 
  51.                     out.close();*/  
  52.                     request.setAttribute("msg""<script language='javascript'>window.alert('成功加入購物車!');</script>");  
  53.                     request.getRequestDispatcher("BookInfo/"+b.getBookId()+".jsp").forward(request, response);  
  54.                 }  
  55.                 else{     
  56.                     request.setAttribute("msg""<script language='javascript'>window.alert('加入購物車失敗!');</script>");  
  57.                     request.getRequestDispatcher("BookInfo/"+b.getBookId()+".jsp").forward(request, response);  
  58.                 }  
  59.                   
  60.             }             
  61.         }  
  62.     }  
  63.   
  64. }  

6.2用戶註冊和用戶登錄功能

在用戶登錄使用之前用戶首先要註冊,註冊過程我採用的是爲每個用戶新建一張表,這張表就代表了該用戶的購物車,存放的是該用戶選購的書籍

Register.jsp是顯示註冊的代碼

[html]  view plain  copy
 print ?
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2.   
  3. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  4. <html>  
  5.   <head>  
  6.     <title>用戶註冊</title>  
  7.     <!-- 
  8.     <link rel="stylesheet" type="text/css" href="styles.css"> 
  9.     -->  
  10.     <script type="text/javascript">  
  11.           var select=document.getElementByName("header");  
  12.           var options=select.getElementsByTagName("option");  
  13.           var placeholder=document.getElementsByName("place");  
  14.           function selectheader(){  
  15.                placeholder.src=select.value;  
  16.                  
  17.           }  
  18.     </script>  
  19.     <script type="text/javascript">  
  20.        function login(){  
  21.             if(document.registerform.ID.value==""){  
  22.               window.alert("賬號不能爲空!");  
  23.               return ;  
  24.             }  
  25.             if(document.registerform.Password.value==""){  
  26.               window.alert("密碼不能爲空!");  
  27.               return ;  
  28.             }  
  29.             registerform.submit();  
  30.        }  
  31.         function cancelregister(){  
  32.             document.registerform.method="post";  
  33.             document.registerform.target="_top";  
  34.             document.registerform.action="http://localhost:8080/ShoppingCart/frame.jsp";  
  35.             document.registerform.submit();  
  36.         }  
  37.          
  38.     </script>  
  39.   </head>  
  40.   <body bgcolor="#98FB98">  
  41.     <br><br><br><br>  
  42.     <form action="RegServlet" name="registerform" method="post">  
  43.                  
  44.        <table align="center"  width="300" >  
  45.          <tr>  
  46.             <td colspan="2" align="center" style="color:#00F;font-size;36px" rowspan="1"><b>用戶註冊</b></td>  
  47.          </tr>  
  48.          <tr>  
  49.             <td>賬    號:</td>  
  50.             <td><input name="ID" type="text" > </td>  
  51.          </tr>  
  52.          <tr>  
  53.             <td>密    碼:</td>  
  54.             <td><input name="Password" type="password" > </td>  
  55.          </tr>  
  56.          <tr>  
  57.             <td>性    別:</td>  
  58.             <td><input name="Sex" type="radio" value="男">男 <input name="Sex" type="radio" value="女"></td><!--單選按鈕-->  
  59.          </tr>  
  60.          <tr>  
  61.            <td>電話號碼:</td>  
  62.            <td><input name="Phone" type="text"/></td>  
  63.          </tr>  
  64.         <tr>  
  65.             <td>家    鄉:</td>  
  66.             <td>  
  67.               <select name="Home" ><!--下拉列表-->  
  68.                 <option value="北    京">北     京</option>  
  69.                 <option value="上   海">上   海</option>  
  70.                 <option value="廣   州">廣   州</option>  
  71.                 <option value="深    圳">深    圳</option>               
  72.               </select>  
  73.              </td>  
  74.          </tr>  
  75.          <tr>  
  76.            <td>電子郵件:</td>  
  77.            <td><input name="Email" type="text"/></td>  
  78.          </tr>  
  79.          <tr>  
  80.              <td>上傳頭像:</td>  
  81.              <td >  
  82.                 <div  style="border:1px solid;width:50px;height:50px;" >  
  83.                    <img name="place" src="Sheader/1.jpg" width="50" height="50"></img>                 
  84.                  </div>    
  85.                   <select name="Header" style="width:50px;" onclick="selectheader()"><!--下拉列表-->  
  86.                      <option value="Sheader/1.jpg" >1</option>  
  87.                      <option value="Sheader/2.jpg" >2</option>  
  88.                      <option value="Sheader/3.jpg" >3</option>  
  89.                      <option value="Sheader/4.jpg" >4</option>  
  90.                      <option value="Sheader/5.jpg" >5</option>      
  91.                      <option value="Sheader/6.jpg" >6</option>      
  92.                      <option value="Sheader/7.jpg" >7</option>      
  93.                      <option value="Sheader/8.jpg" >8</option>      
  94.                      <option value="Sheader/9.jpg" >9</option>      
  95.                      <option value="Sheader/10.jpg" >10</option>                   
  96.                 </select>                                                                     
  97.              </td>               
  98.          </tr>  
  99.          <tr>  
  100.             <td></td>  
  101.             <td><input type="submit" value=" 注    冊 " > <input type="button" value=" 取    消 "  onclick="cancelregister()"></td>  
  102.          </tr>  
  103.        </table>           
  104.      </form>  
  105.   </body>  
  106. </html>  
結果圖:


該註冊頁面點擊「取消」會返回顯示書籍的主頁面,點擊「註冊」請求提交到RegServlet,註冊成功之後會彈出一個註冊成功提示框並且數據庫會生成以賬號爲表名的表:


RegServlet.java

[java]  view plain  copy
 print ?
  1. package com.servlets;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.PrintWriter;  
  5. import java.sql.Connection;  
  6. import java.sql.PreparedStatement;  
  7. import java.sql.SQLException;  
  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.   
  14. import com.Dao.UserDao;  
  15. import com.tools.DBConnection;  
  16.   
  17. public class RegServlet extends HttpServlet {  
  18.       
  19.   
  20.     private static final long serialVersionUID = 1L;  
  21.   
  22.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  23.             throws ServletException, IOException {  
  24.            request.setCharacterEncoding("UTF-8");  
  25.            response.setCharacterEncoding("UTF-8");  
  26.            response.setContentType("text/html");  
  27.              
  28.            String id= request.getParameter("ID");  
  29.            String password=request.getParameter("Password");  
  30.            String sex= request.getParameter("Sex");  
  31.            String phone=request.getParameter("Phone");  
  32.            String home=request.getParameter("Home");  
  33.            String email=request.getParameter("Email");  
  34.            String header=request.getParameter("Header");  
  35.              
  36.            DBConnection DB=new DBConnection();  
  37.            Connection conn=null;  
  38.            conn=DB.getCon();  
  39.      if(conn!=null){      
  40.         try {  
  41.              UserDao dao=new UserDao();  
  42.             if(!dao.isContainUser(id)){//是否存在用戶                
  43.                 String sql="insert into users values(?,?,?,?,?,?,?)";  
  44.                 PreparedStatement pstm=conn.prepareStatement(sql);  
  45.                 pstm.setString(1, id);  
  46.                 pstm.setString(2, password);  
  47.                 pstm.setString(3, sex);  
  48.                 pstm.setString(4, phone);  
  49.                 pstm.setString(5, home);  
  50.                 pstm.setString(6, email);  
  51.                 pstm.setString(7, header);  
  52.                 pstm.executeUpdate();  
  53.                 System.out.println("註冊成功!");  
  54.                 //同時新建一張購車表,即每個用戶註冊成功都會建一張表  
  55.                 String sql1="create table "+id+"(ID int(20),Name varchar(20),Price varchar(20),Num int(20),Total int(20),primary key(ID))";  
  56.                 PreparedStatement pstm1=conn.prepareStatement(sql1);  
  57.                 pstm1.executeUpdate();  
  58.                 response.sendRedirect("Http://localhost:8080/ShoppingCart/PageQueryServlet");//登錄成功後重定向到books界面  
  59.             }  
  60.             else{  
  61.                 PrintWriter out=response.getWriter();  
  62.                 out.print("<script language='javascript'>window.alert('註冊失敗!');</script>");               
  63.                 out.flush();  
  64.                 out.close();  
  65.                 System.out.println("用戶已存在!");  
  66.             }  
  67.                   
  68.              
  69.         } catch (SQLException e) {  
  70.             // TODO Auto-generated catch block  
  71.             e.printStackTrace();  
  72.         }  
  73.              
  74.     }  
  75.     }  
  76. }  

Bug分析:

本來想搞個上傳頭像的功能,但是感覺圖片規格大小之類的技術不太會,只想出了使用剪輯好了的圖片作爲備選項,想實現選中了某個頭像就更換顯示對應的頭像,這涉及了web前端的JavaScript知識,我只懂一點點,所以就沒有修改了……

用戶登錄功能:

Login.jsp

[html]  view plain  copy
 print ?
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2.   
  3. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  4. <html>  
  5.   <head>  
  6.     <title>網上書店</title>  
  7.       <script language="javascript" src="JS/AjaxRequest.js"></script>  
  8.      <!--javascript語言寫的代碼塊-->  
  9.     <script type="text/javascript">  
  10.        function login(){  
  11.             if(document.loginform.id.value==""){  
  12.               window.alert("賬號不能爲空!");  
  13.               return ;  
  14.             }  
  15.             if(document.loginform.password.value==""){  
  16.               window.alert("密碼不能爲空!");  
  17.               return ;  
  18.             }  
  19.             loginform.submit();  
  20.        }  
  21.         function register(){  
  22.             document.loginform.method="post";  
  23.             document.loginform.target="rightframe";  
  24.             document.loginform.action="register.jsp";  
  25.             document.loginform.submit();  
  26.         }  
  27.          
  28.     </script>  
  29.      <script type="text/javascript">  
  30.        /***********錯誤處理方法*********/  
  31.        function onerror(){  
  32.          alert("您的操作有誤!");  
  33.        }  
  34.         /***********實例化ajax對象的方法*********/  
  35.        function getInfo(){  
  36.            var loader=new net.AjaxRequest("getInfo.jsp?nocache="+new Date().getTime(),deal_getInfo,onerror,"GET");  
  37.              
  38.        }  
  39.         /***********回調函數*********/  
  40.        function deal_getInfo(){  
  41.           document.getElementById("showInfo").innerHTML=this.req.responseText;  
  42.        }  
  43.          
  44.        window.onload=function(){  
  45.             getInfo();  //調用getInfo()方法獲取公告信息  
  46.             window.setInterval("getInfo()", 600000);    //每隔10分鐘調用一次getInfo()方法  
  47.        }  
  48.      </script>  
  49.      <style type="text/css">  
  50.         a:link{color:red;text-decoration:none}/*未訪問,紅色,無下劃線*/  
  51.         a:active{color:blue;}/*激活,紅色*/  
  52.         a:visited{color:yellow;text-decoration:none}/*已訪問,紫色,無下劃線*/  
  53.         a:hover{color:blue;text-decoration:underline}/*鼠標移動上面,藍色,下劃線*/  
  54.      </style>  
  55.   </head>  
  56.   <body bgcolor="#98FB98" >  
  57.        <form action="LoginServlet" name="loginform" method="post">  
  58.          <h2 align="center" style=" font-family:隸書">歡迎登陸網上書店系統</h2><br>           
  59.        <table align="center" style="border:1px solid">  
  60.          <tr>  
  61.             <td><font color="blue"><b>賬 號:</b></font></td>  
  62.             <td><input name="id" type="text"> </td>  
  63.          </tr>  
  64.          <tr>  
  65.             <td><font color="blue"><b>密 碼:</b></font></td>  
  66.             <td><input name="password" type="password" size="20"> </td>  
  67.          </tr>  
  68.          <tr>  
  69.             <td></td>  
  70.             <td><input type="button" value="登  錄" onclick="login()">  
  71.                   
  72.              <input type="button" value="立即註冊" onclick="register()">    
  73.             </td>            
  74.          </tr>  
  75.        </table>            
  76.      </form>  
  77.       <table align="center" style="border:1px solid">  
  78.        <tr bgcolor="#FF0000">  
  79.           <td colspan="2" >  
  80.                                   公告信息:  
  81.           </td>  
  82.        </tr>   
  83.          <tr >  
  84.             <td colspan="2" width="215" height="100">         
  85.                 <marquee direction="up" scrollamount="3" onmouseout="this.start()" onmouseover="this.stop()">  
  86.                   <div id="showInfo" ></div>  
  87.                 </marquee>  
  88.             </td>  
  89.          </tr>  
  90.          <tr bgcolor="#FF0000">  
  91.           <td colspan="2" >  
  92.                                   友情鏈接:  
  93.           </td>  
  94.        </tr>   
  95.        <tr >  
  96.           <td colspan="2" >  
  97.             <a href="http://www.hust.edu.cn/" target="_blank"><font face="隸書" color="#FF4500" size="4">華中科技大學</font></a><br>  
  98.             <a href="http://portal.ccnu.edu.cn/" target="_blank"><font face="隸書" color="#FF4500" size="4">華中師範大學</font></a><br>  
  99.             <a href="http://www.cug.edu.cn/new/" target="_blank"><font face="隸書" color="#FF4500" size="4">中國地質大學</font></a><br>  
  100.             <a href="http://www.whut.edu.cn/2015web/index.htm" target="_blank"><font face="隸書" color="#FF4500" size="4">武漢理工大學</font></a>                             
  101.           </td>  
  102.        </tr>   
  103.        </table>  
  104.   </body>  
  105. </html>  

該頁面有三部分,登錄框,公告信息,友情鏈接。

登錄框很簡單form提交到LoginServlet就可以了,在LoginServlet中查詢數據庫判斷等操作:

LoginServlet.java

[java]  view plain  copy
 print ?
  1. package com.servlets;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.PrintWriter;  
  5. import java.util.List;  
  6.   
  7. import javax.servlet.ServletException;  
  8. import javax.servlet.http.HttpServlet;  
  9. import javax.servlet.http.HttpServletRequest;  
  10. import javax.servlet.http.HttpServletResponse;  
  11. import javax.servlet.http.HttpSession;  
  12.   
  13. import com.Dao.BookDao;  
  14. import com.Dao.UserDao;  
  15. import com.beans.Book;  
  16. import com.beans.User;  
  17.   
  18. public class LoginServlet extends HttpServlet {  
  19.   
  20.     private static final long serialVersionUID = 1L;  
  21.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  22.         doPost(request, response);  
  23.     }  
  24.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  25.             throws ServletException, IOException {  
  26.         request.setCharacterEncoding("UTF-8");  
  27.         response.setCharacterEncoding("UTF-8");  
  28.         response.setContentType("text/html");  
  29.         System.out.println("接收數據");  
  30.         String id=request.getParameter("id");//獲得用戶名  
  31.         String password=request.getParameter("password");//獲得密碼  
  32.         UserDao dao=new UserDao();  
  33.         BookDao bdao=new BookDao();  
  34.         User user=null;  
  35.         user=dao.getUser(id, password);  
  36.         HttpSession session=request.getSession();  
  37.           
  38.         if(user!=null){  
  39.             System.out.println("用戶已查到");  
  40.             session.setAttribute("userid",user.getID());//把查到的用戶放進session中,便於登錄檢查         
  41.             response.sendRedirect("loginsuccess.jsp");  
  42.         }  
  43.         else  
  44.         {  
  45.             PrintWriter out=response.getWriter();  
  46.             out.print("<script type='text/javascript'>");  
  47.             out.print("window.alert('用戶名或密碼不正確!');");  
  48.             out.print("</script>");  
  49.             out.flush();  
  50.             out.close();  
  51.         }  
  52.          
  53.     }  
  54.   
  55. }  

公告信息採用Ajax技術,不刷新頁面更新

關鍵代碼:

[html]  view plain  copy
 print ?
  1. <tr bgcolor="#FF0000">  
  2.           <td colspan="2" >  
  3.                 公告信息:  
  4.           </td>  
  5.        </tr>   
  6.          <tr >  
  7.             <td colspan="2" width="215" height="100">         
  8.                 <marquee direction="up" scrollamount="3" onmouseout="this.start()" onmouseover="this.stop()">  
  9.                   <div id="showInfo" ></div>  
  10.                 </marquee>  
  11.             </td>  
  12.          </tr>  

主要是javascript代碼

[javascript]  view plain  copy
 print ?
  1. <script type="text/javascript">  
  2.        /***********錯誤處理方法*********/  
  3.        function onerror(){  
  4.          alert("您的操作有誤!");  
  5.        }  
  6.         /***********實例化ajax對象的方法*********/  
  7.        function getInfo(){  
  8.            var loader=new net.AjaxRequest("getInfo.jsp?nocache="+new Date().getTime(),deal_getInfo,onerror,"GET");  
  9.              
  10.        }  
  11.         /***********回調函數*********/  
  12.        function deal_getInfo(){  
  13.           document.getElementById("showInfo").innerHTML=this.req.responseText;  
  14.        }  
  15.          
  16.        window.onload=function(){  
  17.             getInfo();  //調用getInfo()方法獲取公告信息  
  18.             window.setInterval("getInfo()", 600000);    //每隔10分鐘調用一次getInfo()方法  
  19.        }  
  20.      </script>  
結果圖:

6.3查看購物車,商品結算和生成訂單功能

點擊「查看我的購物車」,表單提交到CartServlet,在此CartServlet中查詢該用戶的購物車表,查詢所有已添加到購物車的書籍,並請求轉發到Carts.jsp

CartServlet.java

[java]  view plain  copy
 print ?
  1. package com.servlets;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.PrintWriter;  
  5. import java.util.List;  
  6.   
  7. import javax.servlet.ServletException;  
  8. import javax.servlet.http.HttpServlet;  
  9. import javax.servlet.http.HttpServletRequest;  
  10. import javax.servlet.http.HttpServletResponse;  
  11. import javax.servlet.http.HttpSession;  
  12.   
  13. import com.Dao.CartDao;  
  14. import com.beans.CartBook;  
  15.   
  16. public class CartServlet extends HttpServlet {  
  17.   
  18.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  19.         doPost(request, response);  
  20.     }  
  21.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  22.             throws ServletException, IOException {  
  23.             HttpSession session=request.getSession();  
  24.             String userId=(String) session.getAttribute("userid");//登錄成功後用戶的Id放在session中  
  25.             System.out.println(userId);  
  26.               
  27.             String m=request.getParameter("m");//刪除書籍的時候判斷標記  
  28.             if(m!=null){  
  29.                  if(m.equals("1")){  
  30.                   request.setAttribute("msg""<script language='javascript'>window.alert('成功刪除!');</script>");  
  31.                }  
  32.                else if(m.equals("0")){  
  33.                 request.setAttribute("msg""<script language='javascript'>window.alert('刪除失敗!');</script>");  
  34.                }  
  35.                else if(m.equals("2")){  
  36.                    request.setAttribute("msg""<script language='javascript'>window.alert('清空購物車失敗!');</script>");  
  37.                }  
  38.             }  
  39.                        
  40.             CartDao ccdao=new CartDao();  
  41.             List<CartBook> list=ccdao.getAllCartBooks((String)session.getAttribute("userid"));  
  42.             request.setAttribute("booklist", list);//把已購買的書單放進request中  
  43.             request.getRequestDispatcher("Carts.jsp").forward(request, response);             
  44.     }  
  45.       
  46. }  

Carts.jsp

[html]  view plain  copy
 print ?
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%@ page import="com.beans.CartBook" import="com.Dao.CartDao"%>  
  3. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  4. <html>  
  5.   <head>  
  6.     <title>購物車</title>  
  7.     <!-- 
  8.     <link rel="stylesheet" type="text/css" href="styles.css"> 
  9.     -->  
  10.     <style type="text/css">  
  11.         a:link{color:#FF4500;text-decoration:none}/*未訪問,紅色,無下劃線*/  
  12.         a:active{color:blue;}/*激活,紅色*/  
  13.         a:visited{color:red;text-decoration:none}/*已訪問,紫色,無下劃線*/  
  14.         a:hover{color:yellow;text-decoration:underline}/*鼠標移動上面,藍色,下劃線*/  
  15.     </style>  
  16.   
  17.   </head>    
  18.   <body bgcolor="#98FB98">  
  19.     <br> <br> <br>  
  20.        
  21.        <table align="center"   width="900" >  
  22.           <tr bgcolor="#ff0000" >  
  23.              <td colspan="8"><font face="隸書" size="5" >我的購物車</font></td>  
  24.           </tr>  
  25.           <tr>  
  26.             <td width="60" align="center" ><font color="blue"><b>商品</b></font></td>  
  27.             <td align="center" ><font color="blue"><b>商品名稱</b></font></td>  
  28.             <td align="center"><font color="blue"><b>價格</b></font></td>  
  29.              <td align="center" width="20"></td>  
  30.             <td align="center" width="60"><font color="blue"><b>數量</b></font></td>  
  31.             <td align="center" width="20"></td>  
  32.             <td align="center"><font color="blue"><b>總價</b></font></td>            
  33.             <td align="center"><font color="blue"><b>操作</b></font></td>  
  34.           </tr>  
  35.            <tr>  
  36.             <td colspan="8"><hr></td>  
  37.           </tr>  
  38.           <%   
  39.              List<CartBook> list=(List<CartBook>)request.getAttribute("booklist");  
  40.               String userid=(String) session.getAttribute("userid");  
  41.               CartDao cdao=new CartDao();  
  42.               int total=cdao.getTotalPrice(userid);   
  43.              // int total=0;    
  44.               int i=1;        
  45.               System.out.print(list.size());            
  46.           %>  
  47.           <%   
  48.             if(list.size()==0){  
  49.           %>   
  50.             <tr>  
  51.                <td colspan="8" align="center" height="30">請添加書籍!</td>  
  52.             </tr>  
  53.           <%       
  54.             }  
  55.             else{  
  56.               
  57.              for(i=0;i<list.size();i++){  
  58.           %>  
  59.            <tr align="center">  
  60.              <td height="80" width="60"><img src="Simages/<%=list.get(i).getBookId()-1 %>.jpg"></td>  
  61.              <td align="center"><%=list.get(i).getName() %></td>  
  62.              <td align="center"><%=list.get(i).getPrice()%></td>  
  63.              <td align="center" width="20">                           
  64.              <form action="UpdateNumServlet?bookidtext=<%=list.get(i).getBookId() %>" method="post" name="numform"><!--減數量 -->  
  65.                 <br>   
  66.                 <input value="-" type="submit" name="sub" >                
  67.                 <input type="hidden" value="-1" name="hid">   
  68.               </form>  
  69.              </td>  
  70.                  
  71.               <td align="center"  width="60">   
  72.                <input type="text"   size="10" readonly  value="<%=list.get(i).getNum() %>" style="text-align:center">   
  73.               </td>  
  74.                 
  75.              <td align="center" width="20">  
  76.              <form action="UpdateNumServlet?bookidtext=<%=list.get(i).getBookId() %>" method="post" ><!-- 加數量 -->   
  77.                 <br>   
  78.                 <input value="+" type="submit" name="add" >  
  79.                 <input type="hidden" value="1" name="hid">   
  80.              </form>       
  81.              </td>  
  82.              <td align="center"><%=list.get(i).getTotal()%></td>  
  83.              <td align="center">  
  84.               <a href="http://localhost:8080/ShoppingCart/DeleteBookServlet?bookid=<%=list.get(i).getBookId()%>">刪除</a>              
  85.              </td>  
  86.            </tr>           
  87.           <%} }%>  
  88.           <tr>  
  89.             <td colspan="8"><hr></td>  
  90.           </tr>  
  91.           <tr>   
  92.              <td width="80">總金額:</td>   
  93.              <td colspan="7"><%=total %></td>  
  94.            </tr>   
  95.           <tr>  
  96.             <td colspan="8"><hr></td>  
  97.           </tr>  
  98.           <tr>  
  99.             <td colspan="2">              
  100.                 
  101.             <a href="ClearCartServlet">清空購物車</a>  
  102.             </td>  
  103.             <td align="right"  colspan="6" valign="bottom">  
  104.               <form action="orders.jsp" method="post">  
  105.                  <br>  
  106.                 <input value="商品結算" type="submit">   <a href="http://localhost:8080/ShoppingCart/PageQueryServlet">返回繼續購物</a>  
  107.               </form>            
  108.             </td>  
  109.           </tr>    
  110.           <tr>  
  111.             <td colspan="8"><hr></td>  
  112.           </tr>         
  113.        </table>  
  114.         <%   
  115.          String msg=(String)request.getAttribute("msg");  //彈窗信息  
  116.       if(msg!=null){ %>  
  117.               <%=msg %>  
  118.          <%} %>  
  119.   </body>  
  120. </html>  

購物車結果圖:


在這個購物車頁面中會有比較多的功能,比如:刪除書籍,清空購物車,修改書籍數量,商品結算等功能

刪除書籍:
點擊「刪除」請求提交到DeleteBookServlet,該Servlet中實現刪除操作

DeleteBookServlet.java

[java]  view plain  copy
 print ?
  1. package com.servlets;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.PrintWriter;  
  5.   
  6. import javax.servlet.ServletException;  
  7. import javax.servlet.http.HttpServlet;  
  8. import javax.servlet.http.HttpServletRequest;  
  9. import javax.servlet.http.HttpServletResponse;  
  10. import javax.servlet.http.HttpSession;  
  11.   
  12. import com.Dao.CartDao;  
  13.   
  14. public class DeleteBookServlet extends HttpServlet {  
  15.   
  16.     private static final long serialVersionUID = 1L;  
  17.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  18.         doPost(request, response);  
  19.     }  
  20.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  21.             throws ServletException, IOException {  
  22.            request.setCharacterEncoding("UTF-8");  
  23.            response.setCharacterEncoding("UTF-8");  
  24.            HttpSession session=request.getSession();  
  25.            String userid=(String)session.getAttribute("userid");  
  26.            String bookid=request.getParameter("bookid");  
  27.              
  28.            CartDao cartdao=new CartDao();  
  29.            boolean b=cartdao.DeleteBook(userid, Integer.parseInt(bookid));//刪除書籍  
  30.            if(b){  
  31.                System.out.println("刪除成功");        
  32.                response.sendRedirect("http://localhost:8080/ShoppingCart/CartServlet?m=1");  
  33.            }  
  34.            else{  
  35.                  
  36.                response.sendRedirect("http://localhost:8080/ShoppingCart/CartServlet?m=0");  
  37.            }          
  38.     }  
  39.   
  40. }  

清空購物車:

點擊「清空購物車」,請求提交到ClearCartServlet

ClearCartServlet.java

[java]  view plain  copy
 print ?
  1. package com.servlets;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.PrintWriter;  
  5.   
  6. import javax.servlet.ServletException;  
  7. import javax.servlet.http.HttpServlet;  
  8. import javax.servlet.http.HttpServletRequest;  
  9. import javax.servlet.http.HttpServletResponse;  
  10. import javax.servlet.http.HttpSession;  
  11.   
  12. import com.Dao.CartDao;  
  13.   
  14. public class ClearCartServlet extends HttpServlet {  
  15.   
  16.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  17.         doPost(request, response);  
  18.     }  
  19.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  20.             throws ServletException, IOException {  
  21.              
  22.            HttpSession session=request.getSession();  
  23.            String userid=(String)session.getAttribute("userid");  
  24.              
  25.            CartDao cd=new CartDao();  
  26.             boolean b=cd.ClearCartBook(userid);  
  27.             if(b){  
  28.                 response.sendRedirect("http://localhost:8080/ShoppingCart/CartServlet");  
  29.             }  
  30.             else{  
  31.                 response.sendRedirect("http://localhost:8080/ShoppingCart/CartServlet?m=2");  
  32.             }  
  33.     }  
  34.   
  35. }  

修改書籍數量:點擊「+」/「-」操作,請求提交到UpdateNumServlet,修改數量之後總價格也會變化,修改完成之後重定向到本頁面

UpdateNumServlet.java

[java]  view plain  copy
 print ?
  1. package com.servlets;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.PrintWriter;  
  5.   
  6. import javax.servlet.ServletException;  
  7. import javax.servlet.http.HttpServlet;  
  8. import javax.servlet.http.HttpServletRequest;  
  9. import javax.servlet.http.HttpServletResponse;  
  10. import javax.servlet.http.HttpSession;  
  11.   
  12. import com.Dao.CartDao;  
  13.   
  14. public class UpdateNumServlet extends HttpServlet {  
  15.   
  16.     private static final long serialVersionUID = 1L;  
  17.   
  18.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  19.             throws ServletException, IOException {  
  20.            request.setCharacterEncoding("UTF-8");  
  21.            HttpSession session=request.getSession();  
  22.            String userid=(String)session.getAttribute("userid");  
  23.            int bookid=Integer.parseInt((String)request.getParameter("bookidtext"));  
  24.            String hid=(String)request.getParameter("hid");  
  25.            int dnum=Integer.parseInt(hid);//hid的值是+1,-1  
  26.              
  27.            CartDao cd=new CartDao();  
  28.            cd.ModifyNum(userid, bookid, dnum);  
  29.            System.out.println("進入修改數目servlet");  
  30.            response.sendRedirect("http://localhost:8080/ShoppingCart/CartServlet");  
  31.     }  
  32.   
  33. }  

商品結算:

點擊「商品結算」,請求提交到orders.jsp

[html]  view plain  copy
 print ?
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2.   
  3. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  4. <html>  
  5.   <head>  
  6.     <title>填寫訂單</title>  
  7.     <!-- 
  8.     <link rel="stylesheet" type="text/css" href="styles.css"> 
  9.     -->  
  10.   </head>    
  11.   <body bgcolor="#98FB98">  
  12.       <form action="OrderServlet" method="post">  
  13.       <br><br>  
  14.        <table align="center"  width="900" >  
  15.           <tr>  
  16.             <td colspan="2" bgcolor="#FFC125"><b>填寫訂單信息:</b></td>              
  17.           </tr>  
  18.           <tr>  
  19.             <td colspan="2"><hr></td>  
  20.           </tr>  
  21.           <tr >  
  22.             <td colspan="2" bgcolor="#FFE4B5">收貨人信息</td>  
  23.           </tr>  
  24.           <tr>  
  25.             <td width="150">收  貨  人:</td>  
  26.             <td><input type="text" name="receiver"></td>  
  27.           </tr>  
  28.            <tr>  
  29.             <td width="150">詳細地址:</td>  
  30.             <td><input type="text" name="address" size="70"></td>  
  31.           </tr>  
  32.            <tr>  
  33.             <td width="150">郵政編碼:</td>  
  34.             <td><input type="text" name="post"></td>  
  35.           </tr>  
  36.            <tr>  
  37.             <td width="150">移動電話:</td>  
  38.             <td><input type="text" name="mobile">         固定電話:<input type="text" name="fixphone">(如:027-12345678)</td>  
  39.           </tr>  
  40.           <tr  bgcolor="#FFE4B5">  
  41.              <td colspan="2">送貨方式:</td>  
  42.           </tr>  
  43.           <tr>  
  44.             <td colspan="2" ><input type="radio" name="songhuoway" value="<b>普通快遞送貨上門  。</b>【運費5元】 ">普通快遞送貨上門     
  45.                             送貨時間:  
  46.                    <select name="songhuotime" style="width:150px">  
  47.                          <option value="--請選擇送貨時間--" >--請選擇送貨時間--</colspan="2" ><input type="radio" name="songhuoway" value="<b>普通快遞送貨上門  。</b>【運費5元】 ">普通快遞送貨上門     
  48.                             送貨時間:  
  49.                    <select name="songhuotime" style="width:150px">  
  50.                          <option value="--請選擇送貨時間--" >--請選擇送貨時間--</option>   
  51.                          <option value="送貨時間:三天內." >三天內</option>  
  52.                      &n
相關文章
相關標籤/搜索