基于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的代码

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>喵喵网上书店</title>	
  </head>  
 
   <frameset cols="25%,75%" frameborder="NO" border="0" framespacing="0">
       <frame src="login.jsp" noresize scrolling="no" name="leftframe">     
       <frame src="Http://localhost:8080/ShoppingCart/PageQueryServlet" name="rightframe" noresize scrolling="yes">     
   </frameset>
</html>

PageQueryServlet.java的Servlet是分页显示书籍的代码

package com.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.Dao.PageQueryDao;
import com.beans.Book;

public class PageQueryServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
          int currpage=1;
          if(request.getParameter("page")!=null){
        	  currpage=Integer.parseInt(request.getParameter("page"));
          }
        
         PageQueryDao pagedao=new PageQueryDao();
         List<Book> list=pagedao.getPageList(currpage);//查询当前页记录
         request.setAttribute("list", list); 
         int pages;   //计算查询总页数
         int count=pagedao.FindCounts();
         if(count%Book.PAGE_SIZE==0){
        	 pages=count/Book.PAGE_SIZE;
         }
         else{
        	 pages=count/Book.PAGE_SIZE+1;
         }
         
         StringBuffer sb=new StringBuffer();
         //构建分页条
         for(int i=1;i<=pages;i++){
        	 if(i==currpage){
        		 sb.append("『" + i + "』");
        	 }
        	 else{
        		 sb.append("<a href='PageQueryServlet?page="+i+"'>"+i+"</a>");
        	 }
        	 sb.append(" ");
         }
         request.setAttribute("bar", sb.toString());
         request.getRequestDispatcher("books.jsp").forward(request, response);	//请求转发	
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

Books.jsp是显示书籍

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@page import="java.util.List"%>
<%@page import="com.beans.Book"%><html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>图书信息列表</title>

	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<style type="text/css">
	    a:link{color:#FF4500;text-decoration:none}/*未访问,红色,无下划线*/
	    a:active{color:blue;}/*激活,红色*/
	    a:visited{color:red;text-decoration:none}/*已访问,紫色,无下划线*/
	    a:hover{color:yellow;text-decoration:underline}/*鼠标移动上面,蓝色,下划线*/
	</style>
  </head>
  
  <body bgcolor="#98FB98" >
        <br><br>
       <table align="center" width="900">
          <tr>
             <td align="center" colspan="6" valign="baseline">
                 <h2 style=" font-family:隶书;color:#0A0A0A;font-size:50px">喵喵网上书店</h2>
             </td>
          </tr>
            <%! int i=1,j=1; %>
           <% List<Book> list=(List<Book>)request.getAttribute("list");%>
           <% for(j=1;j<=2;j++){ %>
             <tr >
            <% 
               for(Book b:list){ 
                   if(j==2){
                     if(b.getBookId()<=3||(b.getBookId()>=7&&b.getBookId()<=9)) continue;
                   }                         
             %>         
            <td width="100" height="140"><img src="images/<%=String.valueOf(b.getBookId()-1) %>.jpg"/></td>
            <td width="160"> 
                 <font color="#0000FF" face="隶书">ISDN :<%=b.getBookId() %></font><br>
                 <font color="#0000FF" face="隶书"> 书 名:<%=b.getName() %></font><br>
              	 <font color="#0000FF" face="隶书"> 作 者:<%=b.getAuthor() %></font><br>
              	 <font color="#0000FF" face="隶书">出 版:<%=b.getPublisher() %></font><br>
              	 <font color="#0000FF" face="隶书">价 格:<%=b.getPrice() %> </font><br>   
              	    <a href="BookInfo/<%=b.getBookId()%>.jsp?bookid=<%=b.getBookId()%>">查看详细信息</a>                           
            </td> 
               <% if(b.getBookId()%3==0) break; %>                         
          <%} %>   
          </tr>
          <%} %>         
          <tr>
			<td align="right" colspan="6"><%= request.getAttribute("bar") %></td>          
          </tr>
       </table>
  </body>
</html>
结果图:

基于Servlet&Jsp的网上书店设计(三)_第1张图片

点击“查看详细信息”会把该书的bookId放入request中,然后跳转到相应的书的详细信息页:

Id=1的书的代码,1.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="com.Dao.BookDao" %>
<%@ page import="com.beans.Book" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>三国演义</title>
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<style type="text/css">
	    a:link{color:blue;text-decoration:none}/*未访问,红色,无下划线*/
	    a:active{color:blue;}/*激活,红色*/
	    a:visited{color:yellow;text-decoration:none}/*已访问,紫色,无下划线*/
	    a:hover{color:blue;text-decoration:underline}/*鼠标移动上面,蓝色,下划线*/
	</style>

  </head> 
  <body  bgcolor="#98FB98" >
        <% int bookid=Integer.parseInt(request.getParameter("bookid"));  
            BookDao bookdao=new BookDao();   
            Book b=bookdao.getBookById(bookid);  
            String msg=(String)request.getAttribute("msg");                   
         %>
       
        <br><br><br><br>
      <form action="http://localhost:8080/ShoppingCart/CheckLogin?bookid=<%=b.getBookId() %>" method="post" name="checkform">
        <table align="center"  width="800">
             <tr>
                <td width="100" height="140"><img src="Http://localhost:8080/ShoppingCart/images/<%=String.valueOf(b.getBookId()-1) %>.jpg"/></td>
            	<td > 
                  <font color="#000000" face="隶书" size="4">ISDN :<%=b.getBookId() %></font><br>
                  <font color="#000000" face="隶书" size="4"> 书 名:<%=b.getName() %></font><br>
              	  <font color="#000000" face="隶书" size="4"> 作 者:<%=b.getAuthor() %></font><br>
              	  <font color="#000000" face="隶书" size="4">出 版:<%=b.getPublisher() %></font><br>
              	  <font color="#000000" face="隶书" size="4">价 格:<%=b.getPrice() %> </font><br>                 	                         
                </td> 
             </tr>
             <tr><td colspan="2"> <hr color="#FF0000"></td></tr>  
             
             <tr>
               <td colspan="2"> <h2><font color="#8B0000" face="隶书">简介:</font></h2></td>
             </tr>  
             
             <tr>
               <td colspan="2">  
               <p style="font-family:'楷体'">      《三国演义》是中国第一部长篇章回体历史演义小说,以描写东汉末年的战争为主,反映了魏、蜀、吴三个政治集团之间的政治和军事斗争。分为黄巾之乱、董卓之乱、三国鼎立三大部分。在广阔的背景上,上演了一幕幕气势磅礴的战争场面。</p>
               <p style="font-family:'楷体'">      罗贯中将兵法三十六计融于字里行间,既有情节,也有兵法韬略。本书反映了丰富的历史内容,人物名称、地理名称、主要事件和人物性格与《三国志》基本相同,是在固定形象基础上,进行再发挥,这也是历史演义小说的套路。本书一方面反映了真实的三国历史,照顾到读者希望了解真实历史的需要;另一方面,根据明朝社会的实际情况对三国人物进行了夸张、美化、丑化等等。</p></td>
             </tr>
               
              <tr>
                <td colspan="2" align="right">                
                <input value="加入购物车" type="submit">  <a href="Http://localhost:8080/ShoppingCart/PageQueryServlet">继续购物</a></td>
               </tr>         
        </table>              
     </form>
       <% if(msg!=null){ %>
              <%=msg %>
         <%} %>
  </body>
</html>

结果图:
基于Servlet&Jsp的网上书店设计(三)_第2张图片

在该页面中点击“加入购物车”,请求会提交到CheckLogin的Servlet,在该Servlet中完成检查用户有无登录的操作和将书加入到该用户的购物车的操作。如果用户为登录会“用户为登录”窗口提示信息,如果登录了,就成功加入了该用户的购物车,感觉淘宝的模式有点像,点击该用户的“查看我的购物车”即可看到刚加的书籍。若购物车中有书籍会提示“此书已加入购物车,请勿重复添加!”,只需在购物车中调整购买数量即可。

CheckLogin.java

package com.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.Dao.BookDao;
import com.Dao.CartDao;
import com.beans.Book;

public class CheckLogin extends HttpServlet {
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setCharacterEncoding("gb2312");
        HttpSession session=request.getSession(); 
		//String user=(String) session.getAttribute("user");//从session中获取用户
        
        System.out.println("加入购物车");
		String bookid=request.getParameter("bookid");
		BookDao bookdao=new BookDao();
		Book b=bookdao.getBookById(Integer.parseInt(bookid));//通过传过来的bookid返回书的对象
		
        System.out.println("以获取用户");
		if( session.getAttribute("userid")==null){//如果用户未登录
			System.out.println("用户未空");
			request.setAttribute("msg", "<script language='javascript'>window.alert('用户未登录!');</script>");
 			request.getRequestDispatcher("BookInfo/"+b.getBookId()+".jsp").forward(request, response);
		}
		else{
			//加入购物车的操作			
			CartDao cartdao=new CartDao();
			String userid=(String)session.getAttribute("userid");
			//System.out.println(b.getName());
			//System.out.println((String)session.getAttribute("userid"));	
			boolean cc=cartdao.isContainBook(userid, bookid);
			if(cc){//如果此书已添加
				request.setAttribute("msg", "<script language='javascript'>window.alert('此书已加入购物车,请勿重复添加!');</script>");
				request.getRequestDispatcher("BookInfo/"+b.getBookId()+".jsp").forward(request, response);
			}else{//如果此书没添加
				
				boolean bb=cartdao.InsertBook((String)session.getAttribute("userid"), b);
				if(bb){//如果插入书籍成功
					/*PrintWriter out=response.getWriter();
	     			out.print("<script language='javascript'>window.alert('成功加入购物车!');</script>");    			
	     			out.flush();
	     			out.close();*/
					request.setAttribute("msg", "<script language='javascript'>window.alert('成功加入购物车!');</script>");
					request.getRequestDispatcher("BookInfo/"+b.getBookId()+".jsp").forward(request, response);
				}
				else{	
					request.setAttribute("msg", "<script language='javascript'>window.alert('加入购物车失败!');</script>");
					request.getRequestDispatcher("BookInfo/"+b.getBookId()+".jsp").forward(request, response);
				}
				
			}			
		}
	}

}

6.2用户注册和用户登录功能

在用户登录使用之前用户首先要注册,注册过程我采用的是为每个用户新建一张表,这张表就代表了该用户的购物车,存放的是该用户选购的书籍

Register.jsp是显示注册的代码

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>用户注册</title>
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<script type="text/javascript">
	      var select=document.getElementByName("header");
	      var options=select.getElementsByTagName("option");
	      var placeholder=document.getElementsByName("place");
	      function selectheader(){
	           placeholder.src=select.value;
	           
	      }
	</script>
    <script type="text/javascript">
       function login(){
            if(document.registerform.ID.value==""){
              window.alert("账号不能为空!");
              return ;
            }
            if(document.registerform.Password.value==""){
              window.alert("密码不能为空!");
              return ;
            }
            registerform.submit();
       }
        function cancelregister(){
            document.registerform.method="post";
            document.registerform.target="_top";
            document.registerform.action="http://localhost:8080/ShoppingCart/frame.jsp";
            document.registerform.submit();
        }
       
    </script>
  </head>
  <body bgcolor="#98FB98">
    <br><br><br><br>
    <form action="RegServlet" name="registerform" method="post">
               
       <table align="center"  width="300" >
         <tr>
			<td colspan="2" align="center" style="color:#00F;font-size;36px" rowspan="1"><b>用户注册</b></td>
         </tr>
         <tr>
            <td>账    号:</td>
            <td><input name="ID" type="text" > </td>
         </tr>
         <tr>
            <td>密    码:</td>
            <td><input name="Password" type="password" > </td>
         </tr>
         <tr>
            <td>性    别:</td>
            <td><input name="Sex" type="radio" value="男">男 <input name="Sex" type="radio" value="女">女</td><!--单选按钮-->
         </tr>
         <tr>
           <td>电话号码:</td>
           <td><input name="Phone" type="text"/></td>
         </tr>
        <tr>
            <td>家    乡:</td>
            <td>
              <select name="Home" ><!--下拉列表-->
                <option value="北    京">北     京</option>
                <option value="上   海">上   海</option>
                <option value="广   州">广   州</option>
                <option value="深    圳">深    圳</option>             
              </select>
             </td>
         </tr>
         <tr>
           <td>电子邮件:</td>
           <td><input name="Email" type="text"/></td>
         </tr>
         <tr>
             <td>上传头像:</td>
             <td >
                <div  style="border:1px solid;width:50px;height:50px;" >
                   <img name="place" src="Sheader/1.jpg" width="50" height="50"></img>               
                 </div>  
                  <select name="Header" style="width:50px;" onclick="selectheader()"><!--下拉列表-->
                     <option value="Sheader/1.jpg" >1</option>
                     <option value="Sheader/2.jpg" >2</option>
                     <option value="Sheader/3.jpg" >3</option>
                     <option value="Sheader/4.jpg" >4</option>
                     <option value="Sheader/5.jpg" >5</option>    
                     <option value="Sheader/6.jpg" >6</option>    
                     <option value="Sheader/7.jpg" >7</option>    
                     <option value="Sheader/8.jpg" >8</option>    
                     <option value="Sheader/9.jpg" >9</option>    
                     <option value="Sheader/10.jpg" >10</option>                 
                </select>                                                                   
             </td>             
         </tr>
         <tr>
            <td></td>
            <td><input type="submit" value=" 注    册 " > <input type="button" value=" 取    消 "  onclick="cancelregister()"></td>
         </tr>
       </table>         
     </form>
  </body>
</html>
结果图:

基于Servlet&Jsp的网上书店设计(三)_第3张图片

该注册页面点击“取消”会返回显示书籍的主页面,点击“注册”请求提交到RegServlet,注册成功之后会弹出一个注册成功提示框并且数据库会生成以账号为表名的表:

基于Servlet&Jsp的网上书店设计(三)_第4张图片

RegServlet.java

package com.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.Dao.UserDao;
import com.tools.DBConnection;

public class RegServlet extends HttpServlet {
	

	private static final long serialVersionUID = 1L;

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		   request.setCharacterEncoding("UTF-8");
		   response.setCharacterEncoding("UTF-8");
		   response.setContentType("text/html");
		   
           String id= request.getParameter("ID");
           String password=request.getParameter("Password");
           String sex= request.getParameter("Sex");
           String phone=request.getParameter("Phone");
           String home=request.getParameter("Home");
           String email=request.getParameter("Email");
           String header=request.getParameter("Header");
           
           DBConnection DB=new DBConnection();
           Connection conn=null;
           conn=DB.getCon();
     if(conn!=null){    
        try {
        	 UserDao dao=new UserDao();
            if(!dao.isContainUser(id)){//是否存在用户         	 
             	String sql="insert into users values(?,?,?,?,?,?,?)";
     			PreparedStatement pstm=conn.prepareStatement(sql);
     			pstm.setString(1, id);
     			pstm.setString(2, password);
     			pstm.setString(3, sex);
     			pstm.setString(4, phone);
     			pstm.setString(5, home);
     			pstm.setString(6, email);
     			pstm.setString(7, header);
     			pstm.executeUpdate();
     			System.out.println("注册成功!");
     			//同时新建一张购车表,即每个用户注册成功都会建一张表
     			String sql1="create table "+id+"(ID int(20),Name varchar(20),Price varchar(20),Num int(20),Total int(20),primary key(ID))";
     			PreparedStatement pstm1=conn.prepareStatement(sql1);
     			pstm1.executeUpdate();
     			response.sendRedirect("Http://localhost:8080/ShoppingCart/PageQueryServlet");//登录成功后重定向到books界面
            }
            else{
            	PrintWriter out=response.getWriter();
     			out.print("<script language='javascript'>window.alert('注册失败!');</script>");    			
     			out.flush();
     			out.close();
     			System.out.println("用户已存在!");
            }
            	
           
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
           
	}
	}
}

Bug分析:

本来想搞个上传头像的功能,但是感觉图片规格大小之类的技术不太会,只想出了使用剪辑好了的图片作为备选项,想实现选中了某个头像就更换显示对应的头像,这涉及了web前端的javascript知识,我只懂一点点,所以就没有修改了……

用户登录功能:

Login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>网上书店</title>
      <script language="javascript" src="JS/AjaxRequest.js"></script>
     <!--javascript语言写的代码块-->
    <script type="text/javascript">
       function login(){
            if(document.loginform.id.value==""){
              window.alert("账号不能为空!");
              return ;
            }
            if(document.loginform.password.value==""){
              window.alert("密码不能为空!");
              return ;
            }
            loginform.submit();
       }
        function register(){
            document.loginform.method="post";
            document.loginform.target="rightframe";
            document.loginform.action="register.jsp";
            document.loginform.submit();
        }
       
    </script>
     <script type="text/javascript">
       /***********错误处理方法*********/
       function onerror(){
         alert("您的操作有误!");
       }
        /***********实例化ajax对象的方法*********/
       function getInfo(){
           var loader=new net.AjaxRequest("getInfo.jsp?nocache="+new Date().getTime(),deal_getInfo,onerror,"GET");
           
       }
        /***********回调函数*********/
       function deal_getInfo(){
          document.getElementById("showInfo").innerHTML=this.req.responseText;
       }
       
       window.onload=function(){
	        getInfo();	//调用getInfo()方法获取公告信息
	        window.setInterval("getInfo()", 600000);	//每隔10分钟调用一次getInfo()方法
       }
     </script>
     <style type="text/css">
	    a:link{color:red;text-decoration:none}/*未访问,红色,无下划线*/
	    a:active{color:blue;}/*激活,红色*/
	    a:visited{color:yellow;text-decoration:none}/*已访问,紫色,无下划线*/
	    a:hover{color:blue;text-decoration:underline}/*鼠标移动上面,蓝色,下划线*/
	 </style>
  </head>
  <body bgcolor="#98FB98" >
       <form action="LoginServlet" name="loginform" method="post">
         <h2 align="center" style=" font-family:隶书">欢迎登陆网上书店系统</h2><br>         
       <table align="center" style="border:1px solid">
         <tr>
            <td><font color="blue"><b>账 号:</b></font></td>
            <td><input name="id" type="text"> </td>
         </tr>
         <tr>
            <td><font color="blue"><b>密 码:</b></font></td>
            <td><input name="password" type="password" size="20"> </td>
         </tr>
         <tr>
            <td></td>
            <td><input type="button" value="登  录" onclick="login()">
                
             <input type="button" value="立即注册" onclick="register()">  
            </td>          
         </tr>
       </table>          
     </form>
      <table align="center" style="border:1px solid">
       <tr bgcolor="#FF0000">
          <td colspan="2" >
                                  公告信息:
          </td>
       </tr> 
         <tr >
            <td colspan="2" width="215" height="100">       
                <marquee direction="up" scrollamount="3" onmouseout="this.start()" onmouseover="this.stop()">
		          <div id="showInfo" ></div>
	            </marquee>
            </td>
         </tr>
         <tr bgcolor="#FF0000">
          <td colspan="2" >
                                  友情链接:
          </td>
       </tr> 
       <tr >
          <td colspan="2" >
            <a href="http://www.hust.edu.cn/" target="_blank"><font face="隶书" color="#FF4500" size="4">华中科技大学</font></a><br>
            <a href="http://portal.ccnu.edu.cn/" target="_blank"><font face="隶书" color="#FF4500" size="4">华中师范大学</font></a><br>
            <a href="http://www.cug.edu.cn/new/" target="_blank"><font face="隶书" color="#FF4500" size="4">中国地质大学</font></a><br>
            <a href="http://www.whut.edu.cn/2015web/index.htm" target="_blank"><font face="隶书" color="#FF4500" size="4">武汉理工大学</font></a>                           
          </td>
       </tr> 
       </table>
  </body>
</html>

该页面有三部分,登录框,公告信息,友情链接。

登录框很简单form提交到LoginServlet就可以了,在LoginServlet中查询数据库判断等操作:

LoginServlet.java

package com.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.Dao.BookDao;
import com.Dao.UserDao;
import com.beans.Book;
import com.beans.User;

public class LoginServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");
		System.out.println("接收数据");
		String id=request.getParameter("id");//获得用户名
		String password=request.getParameter("password");//获得密码
		UserDao dao=new UserDao();
		BookDao bdao=new BookDao();
		User user=null;
		user=dao.getUser(id, password);
		HttpSession session=request.getSession();
		
		if(user!=null){
			System.out.println("用户已查到");
			session.setAttribute("userid",user.getID());//把查到的用户放进session中,便于登录检查		
			response.sendRedirect("loginsuccess.jsp");
		}
		else
		{
			PrintWriter out=response.getWriter();
			out.print("<script type='text/javascript'>");
			out.print("window.alert('用户名或密码不正确!');");
 			out.print("</script>");
 			out.flush();
 			out.close();
		}
       
	}

}

公告信息采用Ajax技术,不刷新页面更新

关键代码:

<tr bgcolor="#FF0000">
          <td colspan="2" >
                公告信息:
          </td>
       </tr> 
         <tr >
            <td colspan="2" width="215" height="100">       
                <marquee direction="up" scrollamount="3" onmouseout="this.start()" onmouseover="this.stop()">
		          <div id="showInfo" ></div>
	            </marquee>
            </td>
         </tr>

主要是javascript代码

<script type="text/javascript">
       /***********错误处理方法*********/
       function onerror(){
         alert("您的操作有误!");
       }
        /***********实例化ajax对象的方法*********/
       function getInfo(){
           var loader=new net.AjaxRequest("getInfo.jsp?nocache="+new Date().getTime(),deal_getInfo,onerror,"GET");
           
       }
        /***********回调函数*********/
       function deal_getInfo(){
          document.getElementById("showInfo").innerHTML=this.req.responseText;
       }
       
       window.onload=function(){
	        getInfo();	//调用getInfo()方法获取公告信息
	        window.setInterval("getInfo()", 600000);	//每隔10分钟调用一次getInfo()方法
       }
     </script>
结果图:

基于Servlet&Jsp的网上书店设计(三)_第5张图片基于Servlet&Jsp的网上书店设计(三)_第6张图片

6.3查看购物车,商品结算和生成订单功能

点击“查看我的购物车”,表单提交到CartServlet,在此CartServlet中查询该用户的购物车表,查询所有已添加到购物车的书籍,并请求转发到Carts.jsp

CartServlet.java

package com.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.Dao.CartDao;
import com.beans.CartBook;

public class CartServlet extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
            HttpSession session=request.getSession();
            String userId=(String) session.getAttribute("userid");//登录成功后用户的Id放在session中
            System.out.println(userId);
            
            String m=request.getParameter("m");//删除书籍的时候判断标记
            if(m!=null){
            	 if(m.equals("1")){
               	  request.setAttribute("msg", "<script language='javascript'>window.alert('成功删除!');</script>");
               }
               else if(m.equals("0")){
               	request.setAttribute("msg", "<script language='javascript'>window.alert('删除失败!');</script>");
               }
               else if(m.equals("2")){
            	   request.setAttribute("msg", "<script language='javascript'>window.alert('清空购物车失败!');</script>");
               }
            }
                     
            CartDao ccdao=new CartDao();
            List<CartBook> list=ccdao.getAllCartBooks((String)session.getAttribute("userid"));
            request.setAttribute("booklist", list);//把已购买的书单放进request中
            request.getRequestDispatcher("Carts.jsp").forward(request, response);           
	}
	
}

Carts.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="com.beans.CartBook" import="com.Dao.CartDao"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>购物车</title>
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<style type="text/css">
	    a:link{color:#FF4500;text-decoration:none}/*未访问,红色,无下划线*/
	    a:active{color:blue;}/*激活,红色*/
	    a:visited{color:red;text-decoration:none}/*已访问,紫色,无下划线*/
	    a:hover{color:yellow;text-decoration:underline}/*鼠标移动上面,蓝色,下划线*/
	</style>

  </head>  
  <body bgcolor="#98FB98">
    <br> <br> <br>
     
       <table align="center"   width="900" >
          <tr bgcolor="#ff0000" >
             <td colspan="8"><font face="隶书" size="5" >我的购物车</font></td>
          </tr>
          <tr>
            <td width="60" align="center" ><font color="blue"><b>商品</b></font></td>
            <td align="center" ><font color="blue"><b>商品名称</b></font></td>
            <td align="center"><font color="blue"><b>价格</b></font></td>
             <td align="center" width="20"></td>
            <td align="center" width="60"><font color="blue"><b>数量</b></font></td>
            <td align="center" width="20"></td>
            <td align="center"><font color="blue"><b>总价</b></font></td>          
            <td align="center"><font color="blue"><b>操作</b></font></td>
          </tr>
           <tr>
            <td colspan="8"><hr></td>
          </tr>
          <% 
             List<CartBook> list=(List<CartBook>)request.getAttribute("booklist");
              String userid=(String) session.getAttribute("userid");
              CartDao cdao=new CartDao();
              int total=cdao.getTotalPrice(userid); 
             // int total=0;  
              int i=1;      
              System.out.print(list.size());          
          %>
          <% 
            if(list.size()==0){
          %> 
            <tr>
               <td colspan="8" align="center" height="30">请添加书籍!</td>
            </tr>
          <%     
            }
            else{
            
             for(i=0;i<list.size();i++){
          %>
           <tr align="center">
             <td height="80" width="60"><img src="Simages/<%=list.get(i).getBookId()-1 %>.jpg"></td>
             <td align="center"><%=list.get(i).getName() %></td>
             <td align="center">¥<%=list.get(i).getPrice()%></td>
             <td align="center" width="20">                         
             <form action="UpdateNumServlet?bookidtext=<%=list.get(i).getBookId() %>" method="post" name="numform"><!--减数量 -->
                <br> 
                <input value="-" type="submit" name="sub" >              
                <input type="hidden" value="-1" name="hid"> 
              </form>
             </td>
               
              <td align="center"  width="60"> 
               <input type="text"   size="10" readonly  value="<%=list.get(i).getNum() %>" style="text-align:center"> 
              </td>
              
             <td align="center" width="20">
             <form action="UpdateNumServlet?bookidtext=<%=list.get(i).getBookId() %>" method="post" ><!-- 加数量 --> 
                <br> 
                <input value="+" type="submit" name="add" >
                <input type="hidden" value="1" name="hid"> 
             </form>     
             </td>
             <td align="center">¥<%=list.get(i).getTotal()%></td>
             <td align="center">
              <a href="http://localhost:8080/ShoppingCart/DeleteBookServlet?bookid=<%=list.get(i).getBookId()%>">删除</a>            
             </td>
           </tr>         
          <%} }%>
          <tr>
            <td colspan="8"><hr></td>
          </tr>
          <tr> 
             <td width="80">总金额:</td> 
             <td colspan="7">¥<%=total %></td>
           </tr> 
          <tr>
            <td colspan="8"><hr></td>
          </tr>
          <tr>
            <td colspan="2">            
              
            <a href="ClearCartServlet">清空购物车</a>
            </td>
            <td align="right"  colspan="6" valign="bottom">
              <form action="orders.jsp" method="post">
                 <br>
                <input value="商品结算" type="submit">   <a href="http://localhost:8080/ShoppingCart/PageQueryServlet">返回继续购物</a>
              </form>          
            </td>
          </tr>  
          <tr>
            <td colspan="8"><hr></td>
          </tr>       
       </table>
        <% 
         String msg=(String)request.getAttribute("msg");  //弹窗信息
      if(msg!=null){ %>
              <%=msg %>
         <%} %>
  </body>
</html>

购物车结果图:


在这个购物车页面中会有比较多的功能,比如:删除书籍,清空购物车,修改书籍数量,商品结算等功能

删除书籍:
点击“删除”请求提交到DeleteBookServlet,该Servlet中实现删除操作

DeleteBookServlet.java

package com.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.Dao.CartDao;

public class DeleteBookServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		   request.setCharacterEncoding("UTF-8");
		   response.setCharacterEncoding("UTF-8");
		   HttpSession session=request.getSession();
		   String userid=(String)session.getAttribute("userid");
           String bookid=request.getParameter("bookid");
           
           CartDao cartdao=new CartDao();
           boolean b=cartdao.DeleteBook(userid, Integer.parseInt(bookid));//删除书籍
           if(b){
        	   System.out.println("删除成功");  	
        	   response.sendRedirect("http://localhost:8080/ShoppingCart/CartServlet?m=1");
           }
           else{
        	   
        	   response.sendRedirect("http://localhost:8080/ShoppingCart/CartServlet?m=0");
           }		
	}

}

清空购物车:

点击“清空购物车”,请求提交到ClearCartServlet

ClearCartServlet.java

package com.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.Dao.CartDao;

public class ClearCartServlet extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
           
		   HttpSession session=request.getSession();
		   String userid=(String)session.getAttribute("userid");
		   
		   CartDao cd=new CartDao();
		    boolean b=cd.ClearCartBook(userid);
	        if(b){
	        	response.sendRedirect("http://localhost:8080/ShoppingCart/CartServlet");
	        }
	        else{
	        	response.sendRedirect("http://localhost:8080/ShoppingCart/CartServlet?m=2");
	        }
	}

}

修改书籍数量:点击“+”/“-”操作,请求提交到UpdateNumServlet,修改数量之后总价格也会变化,修改完成之后重定向到本页面

UpdateNumServlet.java

package com.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.Dao.CartDao;

public class UpdateNumServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
           request.setCharacterEncoding("UTF-8");
           HttpSession session=request.getSession();
           String userid=(String)session.getAttribute("userid");
           int bookid=Integer.parseInt((String)request.getParameter("bookidtext"));
           String hid=(String)request.getParameter("hid");
           int dnum=Integer.parseInt(hid);//hid的值是+1,-1
           
           CartDao cd=new CartDao();
           cd.ModifyNum(userid, bookid, dnum);
           System.out.println("进入修改数目servlet");
           response.sendRedirect("http://localhost:8080/ShoppingCart/CartServlet");
	}

}

商品结算:

点击“商品结算”,请求提交到orders.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>填写订单</title>
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>  
  <body bgcolor="#98FB98">
      <form action="OrderServlet" method="post">
      <br><br>
       <table align="center"  width="900" >
          <tr>
            <td colspan="2" bgcolor="#FFC125"><b>填写订单信息:</b></td>            
          </tr>
          <tr>
            <td colspan="2"><hr></td>
          </tr>
          <tr >
            <td colspan="2" bgcolor="#FFE4B5">收货人信息</td>
          </tr>
          <tr>
            <td width="150">收  货  人:</td>
            <td><input type="text" name="receiver"></td>
          </tr>
           <tr>
            <td width="150">详细地址:</td>
            <td><input type="text" name="address" size="70"></td>
          </tr>
           <tr>
            <td width="150">邮政编码:</td>
            <td><input type="text" name="post"></td>
          </tr>
           <tr>
            <td width="150">移动电话:</td>
            <td><input type="text" name="mobile">         固定电话:<input type="text" name="fixphone">(如:027-12345678)</td>
          </tr>
          <tr  bgcolor="#FFE4B5">
             <td colspan="2">送货方式:</td>
          </tr>
          <tr>
            <td colspan="2" ><input type="radio" name="songhuoway" value="<b>普通快递送货上门  。</b>【运费5元】 ">普通快递送货上门   
                            送货时间:
                   <select name="songhuotime" style="width:150px">
                         <option value="--请选择送货时间--" >--请选择送货时间--</option> 
                         <option value="送货时间:三天内." >三天内</option>
                         <option value="送货时间:一周内." >一周内</option>
                         <option value="送货时间:十天内." >十天内</option>                
                   </select>(支持货到付款)【运费5元】
            </td>
          </tr>
          <tr>
              <td colspan="2" ><input type="radio" name="songhuoway" value="<b>普通邮递</b>(不支持货到付款)【运费8元】">普通邮递(不支持货到付款)【运费8元】   </td>
          </tr>
           <tr>
              <td colspan="2" ><input type="radio" name="songhuoway" value="<b>邮政特快专递</b>(不支持货到付款)【运费20元】">邮政特快专递(不支持货到付款)【运费20元】   </td>
          </tr>
          <tr  bgcolor="#FFE4B5">
             <td colspan="2">支付方式:</td>
          </tr>
          <tr>
            <td colspan="2" ><input type="radio" name="payway" value="网上支付">网上支付<br>
                         <input type="radio" name="payway" value="网上支付:通过 <b>工商银行</b>支付">工商银行<br>
                         <input type="radio" name="payway" value="网上支付:通过 <b>中国银行</b>支付">中国银行<br>
                         <input type="radio" name="payway" value="网上支付:通过 <b>建设银行</b>支付">建设银行<br>
                         <input type="radio" name="payway" value="网上支付:通过 <b>支付宝支付</b>支付">支付宝支付
            </td>
          </tr>
           <tr>
              <td colspan="2" ><input type="radio" name="payway" value="货到付款">货到付款   </td>
          </tr>
          <tr>
              <td colspan="2" ><input type="radio" name="payway" value="邮政汇款">邮政汇款   </td>
          </tr>
          <tr>
              <td colspan="2" ><input type="radio" name="payway" value="银行转账">银行转账   </td>
          </tr>
          <tr  bgcolor="#FFE4B5">
             <td colspan="2">给卖家留言:</td>
          </tr>
          <tr >
             <td colspan="2"><input type="text" size="100" name="message"></td>
          </tr>
           <tr>
            <td colspan="2"><hr></td>
          </tr>
          <tr>
             <td align="center" colspan="2"><input type="submit" value="生成订单"></td>
          </tr>
       </table>
       </form>
  </body>
</html>

结果图:




点击”生成订单”,请求提交到OrderServlet,此Servlet需要 封装order.jsp的所有信息,然后请求转发到确认页面

OrderServlet.java

package com.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.Dao.CartDao;
import com.beans.CartBook;

public class OrderServlet extends HttpServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
             request.setCharacterEncoding("UTF-8");
             response.setCharacterEncoding("UTF-8");
             
             String receiver=request.getParameter("receiver");
             String address=request.getParameter("address");
             String post=request.getParameter("post");
             String mobile=request.getParameter("mobile");
             String fixphone=request.getParameter("fixphone");
             String songhuoway=request.getParameter("songhuoway");
             String songhuotime=request.getParameter("songhuotime");
             String payway=request.getParameter("payway");
             String message=request.getParameter("message");
             
             int yunfei=0;
             if(songhuoway.equals("<b>普通快递送货上门  。</b>【运费5元】 ")){
            	 yunfei=5;
             }
             else if(songhuoway.equals("<b>普通邮递</b>(不支持货到付款)【运费8元】")){
            	 yunfei=8;
             }
             else if(songhuoway.equals("<b>邮政特快专递</b>(不支持货到付款)【运费20元】")){
            	 yunfei=20;
             }
             
             Map<String,String> hashmap=new HashMap<String,String>();
             hashmap.put("receiver",receiver);
             hashmap.put("address", address);
             hashmap.put("post", post);            
             hashmap.put("mobile", mobile);
             hashmap.put("fixphone", fixphone);
             hashmap.put("songhuoway", songhuoway);
             hashmap.put("songhuotime", songhuotime);
             hashmap.put("payway", payway);   
             hashmap.put("message", message);
             hashmap.put("yunfei", String.valueOf(yunfei));//把运费也传过去
             request.setAttribute("hashmap", hashmap);//封装订单信息
            
             
             HttpSession session=request.getSession();          
             CartDao ccdao=new CartDao();
             List<CartBook> list=ccdao.getAllCartBooks((String)session.getAttribute("userid"));
             request.setAttribute("booklist", list);//把已购买的书单放进session中
             request.getRequestDispatcher("confirmorder.jsp").forward(request, response);
             
	}

}

基于Servlet&Jsp的网上书店设计(三)_第7张图片

Bug分析:

1,确认页面没有返回按钮。

2,点击“退出登录”之后,虽然在session中销毁了userid,但是右框架页面还停留在之前的页面,不能返回到主页面。

3,当没有注册就登录时,也能到成功登录界面,只不过用户名是“null”,应该给出提示信息

你可能感兴趣的:(servlet,设计)