一个小的项目(购物车项目)

web开发 专栏收录该内容
6 篇文章 0 订阅

针对自己前些日子对jsp的学习,现做些总结,过程中有许多不合理的地方,希望看到这篇博客的大佬们多多指正,感激不尽。该项目是自己根据对MVC开发模式的理解写出来的,大体上实现了模型-视图-控制器的分离,从而增加了程序的可维护性。

MVC:全名是Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,一种软件设计典范,用一种业务逻辑、数据、界面显示分离的方法组织代码,将业务逻辑聚集到一个部件里面,在改进和个性化定制界面及用户交互的同时,不需要重新编写业务逻辑。MVC被独特的发展起来用于映射传统的输入、处理和输出功能在一个逻辑的图形化用户界面的结构中。其中:
Model(模型)是应用程序中用于处理应用程序数据逻辑的部分。
  通常模型对象负责在数据库中存取数据。
View(视图)是应用程序中处理数据显示的部分。
  通常视图是依据模型数据创建的。
Controller(控制器)是应用程序中处理用户交互的部分。
  通常控制器负责从视图读取数据,控制用户输入,并向模型发送数据。


对于用户需求:
0.用户登陆自己的账号
1.在购物大厅页面选择商品,
2.选购商品保存到购物车
3.购买商品

对于项目本身,首先包分四类,

com.zx.controller //控制器,用于拿到web页面上的数据,处理用户交互
com.zx.domain  //users和books的两个类,用于构建用户和书的实例
com.zx.service  //处理业务逻辑,用于与数据库打交道
com.zx.utils  //工具类,帮助处理业务逻辑

除了上述四个包之外,还有处理构建用户视图的jsp文件:

hall.jsp  //购物大厅
myshopping.jsp  //登陆界面
shoppingcart.jsp  //我的购物车
submitMyCart.jsp  //提交我的购物车
termination.jsp  //购买成功

整个程序的架构是这样的:

在这里插入图片描述
在这里插入图片描述

各包内的代码:

 com.zx.controller //控制器,用于拿到web页面上的数据,处理用户交互



	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//处理web界面的信息
		//此处id,pwd是web页面得到的
		String id = request.getParameter("id");
		String pwd = request.getParameter("passwd");
		System.out.println("your id is"+ " "+ id);
		System.out.println("your password is"+ " "+ pwd);
		Users user = new Users();
		user.setId((Integer.parseInt(id)));
		user.setPassword(pwd);
		UsersServise UsersServise = new UsersServise();
		try {
			if (UsersServise.checkUsers(user) == true) {
				//验证成功,进入我的购物大厅
				//成功后开始调书的数据库
				//创建一个购物车
				//拿到这个人
				request.getSession().setAttribute("user", user);//这个地方用session,因为request生命周期非常短
				MyCart myCart = new MyCart();
				request.getSession().setAttribute("myCart", myCart);
				BooksServise bs = new BooksServise();
				ArrayList al = bs.CheckBooks();
				request.setAttribute("books", al);
				request.getRequestDispatcher("/WEB-INF/hall.jsp").forward(request, response);
			} else {
				//验证失败,退回登陆页面
				request.getRequestDispatcher("/WEB-INF/myshopping.jsp").forward(request, response);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}
}

/**
 * 接收或相应用户购买商品的请求
 */

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// 判断是放书还是删除书
		String type = request.getParameter("type");
		if (type.equals("del")) {
			// 拿到删除的书
			String id = request.getParameter("id");
			MyCart myCart = (MyCart) request.getSession().getAttribute("myCart");
			myCart.delBook(id);
			request.setAttribute("booklist", myCart.showMyCart());
			request.setAttribute("totalPrice", myCart.getTotalPrice() + "");
			request.getRequestDispatcher("/WEB-INF/shoppingcart.jsp").forward(request, response);
		} else if (type.equals("add")) {
			// 拿到hall的bookid
			String id = request.getParameter("id");
			System.out.println("id is:" + id);
			// 使用购物车
			MyCart myCart = (MyCart) request.getSession().getAttribute("myCart");
			// 为防止getSession取出的type为空造成的NULLPOINTEXCEPTION,要在之前进行非空判断!
			if (myCart != null) {
				System.out.println("true");
				myCart.addBook(id);
				request.setAttribute("booklist", myCart.showMyCart());
				request.setAttribute("totalPrice", myCart.getTotalPrice() + "");
			}
			// 跳转到购物车页面
			request.getRequestDispatcher("/WEB-INF/shoppingcart.jsp").forward(request, response);
		} else if (type.equals("update")) {
			// 拿到id与书的数量
			String bookId[] = request.getParameterValues("id");
			String bookNums[] = request.getParameterValues("booknums");
			MyCart myCart = (MyCart) request.getSession().getAttribute("myCart");
			for (int i = 0; i < bookId.length; i++) {
				myCart.updateBook(bookId[i], bookNums[i]);
			}
			request.setAttribute("booklist", myCart.showMyCart());
			request.setAttribute("totalPrice", myCart.getTotalPrice() + "");
			request.getRequestDispatcher("/WEB-INF/shoppingcart.jsp").forward(request, response);
		} else if (type.equals("dingdan")) {
			// 提交订单
			MyCart myCart = (MyCart) request.getSession().getAttribute("myCart");
			request.setAttribute("booklist", myCart.showMyCart());
			request.setAttribute("totalPrice", myCart.getTotalPrice() + "");
			request.getRequestDispatcher("/WEB-INF/submitMyCart.jsp").forward(request, response);

		} else if (type.equals("buying")) {
			// 终于买了。。。
			MyCart myCart = (MyCart) request.getSession().getAttribute("myCart");
			BooksServise BooksServise = new BooksServise();
			if(BooksServise.insertBooks(myCart)) {
				request.getRequestDispatcher("/WEB-INF/termination.jsp").forward(request, response);//如果写入数据库成功才跳转
			}
			//request.setAttribute("booklist", myCart.showMyCart());
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}

com.zx.domain
package com.zx.domain;
//商品
public class book {
	private int id;
	private String name;
	private String author;
	private String publishHouse;
	private float price;
	private int nums;
	private int haveBookNums = 1;
	
	public int getHaveBookNums() {
		return haveBookNums;
	}
	public void setHaveBookNums(int haveBookNums) {
		this.haveBookNums = haveBookNums;
	}
	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 getPublishHouse() {
		return publishHouse;
	}
	public void setPublishHouse(String publishHouse) {
		this.publishHouse = publishHouse;
	}
	public float getPrice() {
		return price;
	}
	public void setPrice(float price) {
		this.price = price;
	}
	public int getNums() {
		return nums;
	}
	public void setNums(int nums) {
		this.nums = nums;
	}
	
}

package com.zx.domain;
//用户
public class Users {

	private int id;
	private String name;
	private String password;
	private String email;
	private String tel;
	private String grade;
	
	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 getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getTel() {
		return tel;
	}
	public void setTel(String tel) {
		this.tel = tel;
	}
	public String getGrade() {
		return grade;
	}
	public void setGrade(String grade) {
		this.grade = grade;
	}
	
}

com.zx.service

public class BooksServise {
	//造书,然后存到书包里
	public ArrayList CheckBooks() throws SQLException {
		Book_JDBC bj = new Book_JDBC();
		ResultSet rs = bj.getAllBook();
		int col = rs.getMetaData().getColumnCount();
		ArrayList<book> al = new ArrayList<book>();
		while(rs.next()) {
			book book = new book();
			book.setId((Integer.parseInt(rs.getString(1))));
			book.setName(rs.getString(2));
			book.setAuthor(rs.getString(3));
			book.setPublishHouse(rs.getString(4));
			book.setPrice((Integer.parseInt(rs.getString(5))));
			book.setNums((Integer.parseInt(rs.getString(6))));
			al.add(book);
			}
		return al;
	}
	//get book by Id number.
	public ArrayList GetBookById(String id) throws SQLException {
		Book_JDBC bj = new Book_JDBC();
		ResultSet rs = bj.getBookById(id);
		int col = rs.getMetaData().getColumnCount();
		ArrayList<book> al = new ArrayList<book>();
		while(rs.next()) {
			book book = new book();
			book.setId((Integer.parseInt(rs.getString(1))));
			book.setName(rs.getString(2));
			book.setAuthor(rs.getString(3));
			book.setPublishHouse(rs.getString(4));
			book.setPrice((Integer.parseInt(rs.getString(5))));
			book.setNums((Integer.parseInt(rs.getString(6))));
			al.add(book);
			}
		return al;
	}
	
	//insert books into database.
	public boolean insertBooks(MyCart mycart) {
		Book_JDBC bj = new Book_JDBC();
		if(bj.NewOrder(mycart)) {
			return true;
		}else {
			return false;
		}
	}
}
//处理业务逻辑
//处理和uerstable相关的业务逻辑
public class UsersServise {
	// 验证用户是否合法
	public boolean checkUsers(Users user) throws SQLException {
		// 到数据库验证
		boolean bl = false;
		users_JDBC uj = new users_JDBC();
		int id = user.getId();
		String pwd = user.getPassword();// 网页中得到的密码
		ResultSet rs = uj.getResult(id, pwd);
		if (rs != null) {
			while (rs.next()) {
				String checkpwd = rs.getString(3);// 数据库中的密码
				if (checkpwd.equals(pwd)) {
					user.setEmail(rs.getString(4));
					user.setTel(rs.getString(5));
					user.setGrade(rs.getString(6));
					user.setName(rs.getString(2));
					bl = true;
					break;
				}
			}
		}
		return bl;
	}
}
//我的购物车,从表单传来的数据存在这里
public class MyCart {
	HashMap<String,book> hm = new HashMap<String,book>();
	
	//放书
	public void addBook(String id) {
		if(hm.containsKey(id)) {
			book book = hm.get(id);
			int haveBookNums = book.getHaveBookNums();
			book.setHaveBookNums(haveBookNums+1);		
		}else {	
		 try {
			hm.put(id,(book)new BooksServise().GetBookById(id).get(0));
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		}
	}
	
	//拿走书
	public void delBook(String id) {
		hm.remove(id);
	}
	//更新书
	public void updateBook(String id,String nums) {
		book book = hm.get(id);
		book.setHaveBookNums(Integer.parseInt(nums));
	}
	//全不要了
	public void clearBook() {
		hm.clear();
	}
	
	//看看我都有哪些书
	public ArrayList showMyCart() {
		ArrayList<book> al = new ArrayList<book>();
		//遍历hashmap
		Iterator iterator = hm.keySet().iterator();
		while(iterator.hasNext()) {
			String id =(String)iterator.next();
			book book = hm.get(id);
			al.add(book);
		}
		return al;
	}
	
	//得到购物车中书的总价
	public float getTotalPrice() {
		float total = 0.0f;
		Iterator iterator = hm.keySet().iterator();
		while(iterator.hasNext()) {
			String bookId = (String) iterator.next();
			book book = hm.get(bookId);

			total += book.getPrice() * book.getHaveBookNums();

		}
		return total;
	}
}

com.zx.utils

//与数据库“书”建立连接并获取数据
public class Book_JDBC {

	public static Connection getConn() {
		String driver = "com.mysql.cj.jdbc.Driver";
		String url = "jdbc:mysql://localhost:3306/myshopping?user=root&password=root&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8";
		String username = "root";
		String password = "root";
		Connection conn = null;
		try {
			Class.forName(driver);
			conn = (Connection) DriverManager.getConnection(url, username, password);

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

	// 获取数据库中所有的书
	public static ResultSet getAllBook() {
		Connection conn = getConn(); // 建立连接
		String sql = "select * from booktable";
		PreparedStatement pstmt;
		ResultSet rs = null;
		try {
			pstmt = (PreparedStatement) conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rs;
	}

	// 通过id号获取相应的书
	public ResultSet getBookById(String id) {
		Connection conn = getConn();
		String sql = "select * from booktable where bookid=" + id;
		PreparedStatement pstmt;
		ResultSet rs = null;
		try {
			pstmt = (PreparedStatement) conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rs;
	}

	// 向数据库导入新的订单
	public boolean NewOrder(MyCart mycart) {

		ArrayList<book> al = mycart.showMyCart();
		Connection conn = getConn();
		String sql = "insert into buytable (bookid,bookname,booknums) values(?,?,?)";
		PreparedStatement pstmt = null;
		 int res = 0;
		try {
	        for(int i=0;i<al.size();i++) {
	        pstmt = (PreparedStatement) conn.prepareStatement(sql);
	        pstmt.setInt(1, al.get(i).getId());
	        pstmt.setString(2, al.get(i).getName());
	        pstmt.setInt(3, al.get(i).getHaveBookNums());
	        res = pstmt.executeUpdate(); //executeQury可以用于select,而插入用execute
	        }
	        pstmt.close();
	        conn.close();
	    } catch (SQLException e) {
	        e.printStackTrace();
	    }
		if(res == 1) {
			return true; //等于1说明插入成功
		}else {
			return false;
		}
//与数据库连接的类
public class users_JDBC {

//与数据库连接的方法
	public static Connection getConn() {
		String driver = "com.mysql.cj.jdbc.Driver";
		String url = "jdbc:mysql://localhost:3306/myshopping?user=root&password=root&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8";
		String username = "root";
		String password = "root";
		Connection conn = null;
		try {
			Class.forName(driver);
			conn = (Connection) DriverManager.getConnection(url, username, password);

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

	//取出数据库中所有数据
	public static ResultSet getSelect() {
		Connection conn = getConn();	//建立连接
		String sql = "select * from userstable";
		PreparedStatement pstmt;
		ResultSet rs = null;
		try {
			pstmt = (PreparedStatement) conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rs;
	}
	//取出在数据库中与网页传入数据相等的数据
	public ResultSet getResult(int id,String password) {
		Connection conn = getConn();//建立连接
		String sql = "SELECT * FROM userstable WHERE id ="+ id;
		PreparedStatement pstmt;
		try {
			pstmt = (PreparedStatement) conn.prepareStatement(sql);
			if(pstmt == null) {
				System.out.println("pstmt");
			}
			//1.使用resultSet时要注意rs.next();
			//2.resultSet是一个结果集,不能直接获取信息,rs.getString("xxx")需要循环遍历;
			ResultSet rs = pstmt.executeQuery();//取出数据到set集中         
			return rs;	
		}catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
}

登陆界面:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>登陆界面</title>
</head>
<body>
	<h1>登陆界面</h1>
	<table border="1">
		<form action="/myShopping/goHallUI" method="post">
			<tr><td>用户名:</td><td><input type="text" name="id"></td></tr>
			<tr><td>密码:</td><td><input type="password" name="passwd"></td></tr>
			<tr><td><input type="submit" value="登陆"></td><td><input type="reset" value="重置"></td></tr>			
		</form>
	</table>
</body>
</html>

购物大厅:

<%@	page language="java"
	import="com.zx.service.*,java.sql.ResultSet,java.util.ArrayList,com.zx.domain.*"
	contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>购物大厅</title>
</head>
<body>
	<h1>欢迎光临购物大厅!</h1>
	<form action="??" method="post">
		<table border="1" width="600px">
			<tr>
				<td>书号</td>
				<td>书名</td>
				<td>价格</td>
				<td>出版社</td>
				<td>是否购买</td>
			</tr>
			<%
				ArrayList al = (ArrayList) request.getAttribute("books");  //拿到goHallUI的arraylist
				for (int i = 0; i < al.size(); i++) {
					book book = (book) al.get(i); //构造每一本书的实例
			%>
			<tr>
				<td><%=book.getId()%></td>
				<td><%=book.getName()%></td>
				<td><%=book.getPrice()%></td>
				<td><%=book.getPublishHouse()%></td>
				<td><a href="/myShopping/ShoppingCLServlet?type=add&id=<%=book.getId()%>">点击购买</a></td>
			</tr>
			<%
				}
			%>

		</table>
	</form>

</body>
</html>

购物车:

<%@ page language="java"
	import="com.zx.service.*,java.sql.ResultSet,java.util.ArrayList,com.zx.domain.*"
	contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>我的购物清单</title>
</head>
<body>
	<h1>我的购物车</h1>
	<form action="/myShopping/ShoppingCLServlet?type=update" method="post">
		<table border="1" width="800px">
			<tr>
				<td>BookID</td>
				<td>书名</td>
				<td>价格</td>
				<td>出版社</td>
				<td>剩余数量</td>
				<td>购买数量</td>
				<td>是否删除</td>
			</tr>
			<%
				//显示从hall准备买的书
				ArrayList al = (ArrayList) request.getAttribute("booklist");
				if (al != null) {
					System.out.println("true"); //判断值传进来没
					for (int i = 0; i < al.size(); i++) {
						book book = (book) al.get(i);
						System.out.println(book.getId());
						System.out.println(book.getName());
						System.out.println(book.getPrice());
						System.out.println(book.getPublishHouse());
						System.out.println(book.getNums());
						System.out.println("买书的数量:"+book.getHaveBookNums());
			%><tr>
				<td><%=book.getId()%><input type="hidden" name="id" value=<%=book.getId() %>></td>
				<td><%=book.getName()%></td>
				<td><%=book.getPrice()%></td>
				<td><%=book.getPublishHouse()%></td>
				<td><%=book.getNums()%></td>
				<td><input type="text" name="booknums" value="<%=book.getHaveBookNums()%>"/></td>
				<td><a href="/myShopping/ShoppingCLServlet?type=del&id=<%=book.getId()%>">是否删除</a></td>
			</tr>
			<%
				
				}
				out.println("消费总金额为:"+request.getAttribute("totalPrice")+" 元");
				}
			%>
			<tr>
				<td><input type="submit" value="update"></td>
				<td><a href="/myShopping/ShoppingCLServlet?type=dingdan">提交订单</a></td>
			</tr>
		</table>
	</form>
</body>
</html>

最终购买:

<%@ page language="java" 
	import="com.zx.service.*,java.sql.ResultSet,java.util.ArrayList,com.zx.domain.*"
	contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>submitMyCart</title>
</head>
<body>
	<form action="/myShopping/ShoppingCLServlet?type=buying" method="post">
		<table border="2">
			<%
				Users user =(Users)request.getSession().getAttribute("user");
				if(user != null){
			%>
			<tr>
				<td>您的Id</td>
				<td>您的名字</td>
				<td>您的电话</td>
				<td>您的邮箱</td>
				<td>您的等级</td>
			</tr>
			<tr>
				<td><%=user.getId()%></td>
				<td><%=user.getName()%></td>
				<td><%=user.getTel()%></td>
				<td><%=user.getEmail()%></td>
				<td><%=user.getGrade()%></td>
			</tr>
			<%
			}
			%>
		</table>
		<table border="1">
		<%
			ArrayList al = (ArrayList) request.getAttribute("booklist");
			if(al != null){
				System.out.println("TRUE!");
				for (int i = 0; i < al.size(); i++) {
					book book = (book) al.get(i);
		%><tr>
			<td><%=book.getId()%><input type="hidden" name="id" value=<%=book.getId() %>></td>
			<td><%=book.getName()%></td>
			<td><%=book.getPrice()%></td>
			<td><%=book.getPublishHouse()%></td>
			<td><%=book.getNums()%></td>
			<td><%=book.getHaveBookNums()%> 本</td>
		</tr>
		<%	
			}
			out.println("消费总金额为:"+request.getAttribute("totalPrice")+" 元");
			}
		%>
		</table>
		<input type="submit" value="确认购买" >
	</form>
</body>
</html>

购买成功:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>
	<%
		out.print("购买成功");
	%>
</body>
</html>

index:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>
	<jsp:forward page="WEB-INF/myshopping.jsp"></jsp:forward>
</body>
</html>

数据库:

在这里插入图片描述
在这里插入图片描述

  • 2
    点赞
  • 0
    评论
  • 2
    收藏
  • 打赏
    打赏
  • 扫一扫,分享海报

©️2022 CSDN 皮肤主题:技术黑板 设计师:CSDN官方博客 返回首页

打赏作者

有理想的番茄

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值