create database demodb_info go USE demodb_info GO --drop database demodb_info /****** Object: Table [dbo].[t_book] Script Date: 12/13/2012 17:28:38 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO --drop table [dbo].[t_book] CREATE TABLE [dbo].[t_book]( [id] [int] NOT NULL, [name] [varchar](20) NULL, [auther] [varchar](20) NULL, [press] [varchar](20) NULL, [price] [money] NULL, CONSTRAINT [PK_t_book] PRIMARY KEY CLUSTERED ( [id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO SET ANSI_PADDING OFF GO /****** Script for SelectTopNRows command from SSMS ******/ SELECT TOP 1000 [id] ,[name] ,[auther] ,[press] ,[price] FROM demodb_info.[dbo].[t_book] go --delete FROM demodb_info.[dbo].[t_book] go insert into demodb_info.[dbo].[t_book] values(1,'秘密','拜恩','中国城市出版社',17.3); insert into demodb_info.[dbo].[t_book] values(2,'白鹿原','陈忠实','北京十月文艺出版社',22); insert into demodb_info.[dbo].[t_book] values(3,'青春','韩寒','湖南人民出版社',20.3); insert into demodb_info.[dbo].[t_book] values(4,'追风筝的人','胡赛尼','上海人民出版社',16.3); insert into demodb_info.[dbo].[t_book] values(5,'狼图腾','姜戎','长江文艺出版社',21.1); insert into demodb_info.[dbo].[t_book] values(6,'正能量','理查德 怀斯曼民','湖南文艺出版社',18.5); insert into demodb_info.[dbo].[t_book] values(7,'好妈妈胜过好老师','尹建莉','作家出版社',14.3); insert into demodb_info.[dbo].[t_book] values(8,'你若安好便是晴天','白落梅','中国华侨出版社',17.4); insert into demodb_info.[dbo].[t_book] values(9,'不一样的卡梅拉','克利斯提昂','二十一世纪出版社',26.5); insert into demodb_info.[dbo].[t_book] values(10,'因为痛 所以叫青春','金兰都','广西科学技术出版社',19.7);
package com.Bookinfo.web.util; public class Book { private int id; private String name; private String author; private String press; private double price; public Book(int id, String name, String author, String press, double price) { super(); this.id = id; this.name = name; this.author = author; this.press = press; this.price = price; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getPress() { return press; } public void setPress(String press) { this.press = press; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } }
//登陆的servlet 没有和数据库连接 package com.Bookinfo.Servlet.util; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; 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; public class LoginServlet extends HttpServlet { public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{ PrintWriter out=response.getWriter(); // response.setContentType("text/html;charset=UTF-8"); String name=request.getParameter("loginName"); String pwd=request.getParameter("loginPwd"); //初始化购物车 List<Integer> cart=new ArrayList<Integer>(); if(name.equals("admin") && pwd.equals("123")){ HttpSession sess=request.getSession(); //将购物车放到session对象中 name=new String(name.getBytes("ISO-8859-1"),"UTF-8"); sess.setAttribute("userName", name); sess.setAttribute("cartFrist",cart); //request.getRequestDispatcher("index.jsp").forward(request, response); response.sendRedirect("index.jsp"); }else{ out.println("登录失败!"); } out.flush(); out.close(); } }
package com.Bookinfo.BFace.util; import java.util.List; import com.Bookinfo.web.util.Book; //接口 返回List集合 public interface BookInter { public List<Book> getBook(); }
package com.Bookinfo.BImple.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import com.Bookinfo.BFace.util.BookInter; import com.Bookinfo.web.util.Book; public class Bimple implements BookInter { public Connection conn=null; public Statement stm=null; public ResultSet rs=null; public List<Book> getBook() { // TODO Auto-generated method stub List<Book> books=new ArrayList<Book>(); try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); conn=DriverManager.getConnection("jdbc:sqlserver://localhost:1433;database=demodb_info","sa","svse"); stm=conn.createStatement(); rs=stm.executeQuery("select * from [dbo].[t_book]"); while(rs.next()){ int id=rs.getInt(1); String name=rs.getString(2); String author=rs.getString(3); String press=rs.getString(4); double price=rs.getDouble(5); Book b=new Book(id,name,author,press,price); books.add(b); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return books; } }
package com.Bookinfo.Servlet.util; import java.io.IOException; import java.util.List; import javax.servlet.ServletConfig; 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.Bookinfo.BFace.util.BookInter; import com.Bookinfo.BImple.util.Bimple; import com.Bookinfo.web.util.Book; public class GetServlet extends HttpServlet { private ServletConfig config; public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{ config=this.getServletConfig(); String school=config.getInitParameter("school"); System.out.println(school); response.setContentType("text/html;charset=UTF-8"); HttpSession sess=request.getSession(); BookInter bt=new Bimple(); List<Book> listbobo=bt.getBook(); System.out.println(bt.getBook().size()); sess.setAttribute("book",listbobo); //request.getRequestDispatcher("BookTable.jsp").forward(request, response); response.sendRedirect("BookTable.jsp"); } }
package com.Bookinfo.BFace.util; import java.util.List; import com.Bookinfo.web.util.Book; public interface CartIface { //根据图书ID查血图书信息 public Book getBookById(int id); }
package com.Bookinfo.BImple.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import com.Bookinfo.BFace.util.BookInter; import com.Bookinfo.BFace.util.CartIface; import com.Bookinfo.web.util.Book; public class CartImple implements CartIface { public Connection conn=null; public Statement stm=null; public ResultSet rs=null; public Book getBookById(int id) { // TODO Auto-generated method stub List<Book> books=new ArrayList<Book>(); Book book_cart=null; try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); conn=DriverManager.getConnection("jdbc:sqlserver://localhost:1433;database=demodb_info","sa","svse"); stm=conn.createStatement(); rs=stm.executeQuery("select * from t_book where id='"+id+"'"); while(rs.next()){ Integer bookId=rs.getInt(1); String name=rs.getString(2); String author=rs.getString(3); String press=rs.getString(4); double price=rs.getDouble(5); Book b=new Book(bookId,name,author,press,price); books.add(b); } book_cart=books.get(0); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); }finally{ try { //关闭ResultSet if(rs!=null){rs.close();} //关闭PreparedStatement if(stm!=null){stm.close();} //关闭Connection if(conn!=null){conn.close();} } catch (Exception e) { e.printStackTrace(); } } return book_cart; }
package com.Bookinfo.Servlet.util; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; 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; public class CartServlet extends HttpServlet { /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); HttpSession sess=request.getSession(); String bookId=request.getParameter("bookId");//得到用户购买的图书的id //将用户的图书的id存放到购物车中去中 List<Integer> cart=(List<Integer>)sess.getAttribute("cartFrist"); //将图书id添加进去 cart.add(Integer.parseInt(bookId)); } }
package com.Bookinfo.Servlet.util; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; 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.Bookinfo.BFace.util.CartIface; import com.Bookinfo.BImple.util.CartImple; import com.Bookinfo.web.util.Book; public class CartMessageServlet extends HttpServlet { /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); CartIface ciface=new CartImple(); HttpSession sess=request.getSession(); List<Integer> listCartID=(List<Integer>) sess.getAttribute("cartFrist"); List<Book> listbook=new ArrayList<Book>(); for (int i = 0; i <listCartID.size(); i++) { Book bo=ciface.getBookById(listCartID.get(i)); listbook.add(bo); } sess.setAttribute("CartMessage",listbook); response.sendRedirect("cartMessage.jsp"); } }
<%@ 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>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <a href="Login.jsp">登陆</a> <%=session.getAttribute("userName") %> <a href="bookTable">查看信息</a> <a href="CartMessageServlet">查看购物车</a> </body> </html>
<%@ 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>My JSP 'Login.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <div align="center"><form action="loginUser" method="post"> 用户名: <input type="text" name="loginName"> <br/> 密码: <input type="text" name="loginPwd"> <br/> <input type="submit" value="确定"/> </form></div> </body> </html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <%@ page import="com.Bookinfo.web.util.Book" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'BookTable.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> This is my table page. <br> <hr/> <center> <table> <tr> <td>图书Id</td> <td>图书名称</td> <td>图书作者</td> <td>图书出版社</td> <td>图书价格</td> <td>操作</td> </tr> <% List<Book> listBook=(ArrayList)session.getAttribute("book"); for(int i=0;i<listBook.size();i++){ Book b=listBook.get(i); %> <tr> <td><%=b.getId() %></td> <td><%=b.getName() %></td> <td><%=b.getAuthor() %></td> <td><%=b.getPress() %></td> <td><%=b.getPrice() %></td> <td><a href="CartServlet?bookId=<%=b.getId() %>">购买</a></td> </tr> <% } %> </table> </center> </body> </html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <%@ page import="com.Bookinfo.web.util.Book" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'cartMessage.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <center> <table> <%! double sum=0; %> <tr> <td>图书Id</td> <td>图书名称</td> <td>图书作者</td> <td>图书出版社</td> <td>图书价格</td> <td>操作</td> </tr> <% List<Book> listBook=(ArrayList)session.getAttribute("CartMessage"); sum=0; for(int i=0;i<listBook.size();i++){ Book b=listBook.get(i); sum=sum+b.getPrice(); %> <tr> <td><%=b.getId() %></td> <td><%=b.getName() %></td> <td><%=b.getAuthor() %></td> <td><%=b.getPress() %></td> <td><%=b.getPrice() %></td> <td><a href="#">删除</a></td> </tr> <% } %> <tr> <td clospan="6">总价格:<%=sum %></td> </tr> </table> </center> </body> </html>
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>booktable</servlet-name> <servlet-class>com.Bookinfo.Servlet.util.GetServlet</servlet-class> <init-param> <param-name>school</param-name> <param-value>国资</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>booktable</servlet-name> <url-pattern>/bookTable</url-pattern> </servlet-mapping> <servlet> <servlet-name>loginuser</servlet-name> <servlet-class>com.Bookinfo.Servlet.util.LoginServlet</servlet-class> </servlet> <servlet> <description>将图书ID添加到购物车里面</description> <display-name>将图书添加到购物车</display-name> <servlet-name>CartServlet</servlet-name> <servlet-class>com.Bookinfo.Servlet.util.CartServlet</servlet-class> </servlet> <servlet> <description>根据图书ID将图书信息添加到购物车里面</description> <display-name>将图书全部信息添加到购物车</display-name> <servlet-name>CartMessageServlet</servlet-name> <servlet-class>com.Bookinfo.Servlet.util.CartMessageServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>loginuser</servlet-name> <url-pattern>/loginUser</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>CartServlet</servlet-name> <url-pattern>/CartServlet</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>CartMessageServlet</servlet-name> <url-pattern>/CartMessageServlet</url-pattern> </servlet-mapping> </web-app>