使用JavaBean(DAO和VO)开发购物车
一,实现要求
1.编写一个JavaBean类Book,包含isbn,bookName,auther,publisher,price,amount
属性。用作VO(ValueObject)。
2.编写一个类BookDAO,该类中包含一个方法:
publicArrayListgetAllBook()
该方法访问数据库,查询数据库表book_info,将所有图书以一个数组列表对象的形式返回。
3.改写作业7中的SelectBook.JSP页面,使用BookDAO获得图书数据,并显 示图书列表,单击每本图书后面的“添加到购物车”链接(调用CartServlet),则将相应图书的JavaBean保存在session的购物车对象cart中(由下面的CartJServlet实现)。该页面还包含一个查看购物车超链接,链接到ShowCart.jsp页面,点击该链接显示购物中的信息。如
果购物车非空,该页面还显示一个“清空购物车”的链接,链接到名为ClearCart的Servlet.
4.编写一个Servlet类CartServlet,将SelectBook.JSP中用户选中的图书JavaBean对象,存入session中的购物车cart对象中(cart的数据类型是ArrayList),并返回到SelectBook.JSP页面。
5.编写一个ShowCart.jsp页面,该页面显示购物车cart中用户选择的所有图书图书的书号和书名。
6.编写一个Servlet类ClearCart,其功能是清空购物车。
二、具体代码实现
1.编写book类(VO)
public class Book {
private String isbn;
private String bookName;
private String auther;
private String publisher;
private String price;
private String amount;
/**
* @return the isbon
*/
public String getIsbn() {
return isbn;
}
/**
* @param isbon the isbon to set
*/
public void setIsbn(String isbn) {
this.isbn = isbn;
}
/**
* @return the bookName
*/
public String getBookName() {
return bookName;
}
/**
* @param bookName the bookName to set
*/
public void setBookName(String bookName) {
this.bookName = bookName;
}
/**
* @return the auther
*/
public String getAuther() {
return auther;
}
/**
* @param auther the auther to set
*/
public void setAuther(String auther) {
this.auther = auther;
}
/**
* @return the publisher
*/
public String getPublisher() {
return publisher;
}
/**
* @param publisher the publisher to set
*/
public void setPublisher(String publisher) {
this.publisher = publisher;
}
/**
* @return the price
*/
public String getPrice() {
return price;
}
/**
* @param price the price to set
*/
public void setPrice(String price) {
this.price = price;
}
/**
* @return the amount
*/
public String getAmount() {
return amount;
}
/**
* @param amount the amount to set
*/
public void setAmount(String amount) {
this.amount = amount;
}
}
2.bookDAO(DAO)
package test9;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import com.mysql.jdbc.PreparedStatement;
public class bookDAO {
public ArrayList<Book> queryAllBooks() throws Exception{
ArrayList<Book> books = new ArrayList<Book>();
try {
Class.forName("org.gjt.mm.mysql.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String url ="jdbc:mysql://localhost:3306/bookstore?user=test&password=123456";
Connection conn = null;
try {
conn = DriverManager.getConnection(url);
} catch (SQLException e) {
e.printStackTrace();
}
String sql = "select * from book_info";
PreparedStatement ps = null;
try {
ps = (PreparedStatement) conn.prepareStatement(sql);
} catch (SQLException e) {
e.printStackTrace();
}
try {
ResultSet rs=ps.executeQuery();
while (rs.next())
{
//实例化vo
Book book=new Book();
book.setIsbn(rs.getString("isbn"));
book.setBookName(rs.getString("bookName"));
// book.setAuther(rs.getString("author"));
// book.setPrice(rs.getString("price"));
// book.setAmount(rs.getString("amount"));
// book.setPublisher(rs.getString("publisher"));
books.add(book);
}
rs.close();
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
finally {
try {
if(conn!=null){
conn.close();
conn=null;
}
}catch (Exception ignored) {
}
}
return books;
}
}
3.Cartservlet
package test9;
import test9.Book;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
@WebServlet("/CartServlet")
public class CartServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
HttpSession session = request.getSession();
@SuppressWarnings({
"rawtypes", "rawtypes" })
ArrayList books = (ArrayList)session.getAttribute("books");
if (books==null){
books = new ArrayList();
session.setAttribute("books",books);
}
Book book = new Book();
book.setIsbn(request.getParameter("isbn"));
book.setBookName(request.getParameter("name"));
// book.setAuthor(request.getParameter("auther"));
// book.setPublisher(request.getParameter("publisher"));
// book.setPrice(Integer.parseInt(request.getParameter("price")));
// book.setAmount(Integer.parseInt(request.getParameter("amount")));
// book.setTypeid(Integer.parseInt(request.getParameter("typeid")));
System.out.println(book.toString());
if (book!=null){
books.add(book);
}
ServletContext application = this.getServletContext();
RequestDispatcher rd = application.getRequestDispatcher("/SelectBook.jsp");
rd.forward(request,response);
}
}
4.ClearCart
package test9;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/ClearCart")
public class ClearCart extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ClearCart() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html;charset=UTF-8");
HttpSession session = request.getSession();
ArrayList<Book> books = (ArrayList)session.getAttribute("books");
System.out.println(123);
session.invalidate();
response.sendRedirect(request.getContextPath()+"/SelectBook.jsp");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
5.Delect
package test9;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
@WebServlet("/Delect")
public class Delect extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String s = request.getParameter("name");
System.out.println(s);
HttpSession session = request.getSession();
ArrayList<Book> books = (ArrayList<Book>)session.getAttribute("books");
for(int i=0;i<books.size();i++){
Book book = (Book)books.get(i);
if(book.getIsbn()==s) {
books.remove(books.get(i));
}
session.setAttribute("books",books);
ServletContext application = this.getServletContext();
RequestDispatcher rd = application.getRequestDispatcher("/ShowCart.jsp");
rd.forward(request,response);
}
}}
三、jsp的编写
1.SelectBook
<%@ page import="java.util.*,java.sql.*" language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8" %>
<%@ page import="test9.bookDAO" %>
<%@ page import="test9.Book" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>
<h1 >请选择您需要的图书:</h1>
<table border="1" collspacing="0" collpadding="0" align="center">
<tr>
<th colspan="7">书籍信息</th>
</tr>
<tr>
<th>编号</th>
<th>书名</th>
<th>功能</th>
</tr>
<%
bookDAO bookDao = new bookDAO();
ArrayList<Book> books = bookDao.queryAllBooks();
for(int i=0;i<books.size();i++){
Book book = (Book)books.get(i);
%>
<tr align="center">
<td><%=book.getIsbn() %></td>
<td><%=book.getBookName()%></td>
<td>
<form action="CartServlet" >
<input type="hidden" name="isbn" value="<%=book.getIsbn()%>">
<input type="hidden" name="name" value="<%=book.getBookName()%>">
<button type="submit">添加到购物车</button>
</form>
</td>
</tr>
<% } %>
</table>
<a href="ShowCart.jsp" align="center">查看购物车</a>
</body>
</html>
2.ShowCart
<%@ page import="java.sql.*" language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="test9.Book" %>
<%@ page import="test9.bookDAO" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<table >
<tr>
<th>书号</th>
<th>书名</th>
</tr>
<%
ArrayList<Book> books = (ArrayList)session.getAttribute("books");
for(int i=0;i<books.size();i++){
Book book = (Book)books.get(i);
%>
<tr align="center">
<td><%=book.getIsbn() %></td>
<td><%=book.getBookName()%></td>
<%
}
%>
</table>
<a href="SelectBook.jsp">继续添加</a><br>
<a href="ClearCart">清空</a>
</body>
</html>
四、实现截图
五、Javaweb中DAO和VO的用法
一、VO的使用
VO就是一个普通的JavaBean,而对于JavaBean的一个重要的应用就是将数据库查询的代码,从jsp中移植到JavaBean中。使jsp作为真正的表示层,通过在jsp中调用这个特定的类提供的方法,去对数据库进行操作
二、DAO的使用
DAO叫做Data Access Object类,专门负责对数据库的访问,显然,可以将数据库查询的代码写在DAO 中,通常情况下,可以使用VO(value object)来配合DAO来使用,在DAO中,可以每查询到一条记录,就将其封装为VO中的对象,最后将所有实例化的对象放回到一个集合内进行返回,这样就可以实现层次的分开,降低耦合度,在使用DAO时,必须要导入相应的包才能够实现,接着就可以使用DAO类进行实例对数据库的访问