项目-Java Web购物车-JSP实现

源码地址

点击文章底部打赏后私信发送源码地址
在这里插入图片描述

界面演示

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


介绍(旧)

浏览器打开http://localhost:8080/ShopCart/login.jsp,即可得到如下界面在这里插入图片描述
点击登录(用户名与密码已经在数据库中存在),直接跳到商品列表界面
在这里插入图片描述
点击商品,然后跳转到商品详情界面,这里有个放大图片的效果
在这里插入图片描述
点击加入购物车,跳转到购物车界面,如下图:
在这里插入图片描述

目录结构

在这里插入图片描述
src展开如下图:
在这里插入图片描述

准备工作

创建数据库shop,然后运行SQL文件,通过ShopCart.sql创建,完成后如下图,包含两个表user与product:
在这里插入图片描述
在这里插入图片描述
通过IDE导入项目,然后以tomcat运行

登录注册功能

前端登录页面 login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

<html>
<head>
<title>login</title>
<link href="css/semantic.css"
	rel="stylesheet">
</head>
<body>
	<!-- <p1>test!</p1> -->
	<br>
	<br>
	<br>
	<div class="loginpage">
		<br> <br> <br>
		<h2 align="center">欢迎登录</h2>
		<!--do_login.jsp  -->
		<form name=loginForm action="<%= request.getContextPath() %>/PostServlet" method=post>
			<table align="center">
				<tr>
					<td>用户名:</td>
					<td><div class="ui input focus">
							<input type="text" placeholder="" name=username>
						</div></td>
				</tr>
				<tr>
					<td>密码:</td>
					<td><div class="ui input focus">
							<input type="password" placeholder="" name=pwd>
						</div></td>
				<tr />
				<br>


			</table>
			<div class="submit-p">
				<div class="submit-button">
					<input type="submit" value="login" class="ui primary button" />
				</div>
				<div class="reset-button">
					<input type="reset" value="reset" class="ui button" />
				</div>
			</div>
		</form>

	</div>

	<style>
.loginpage {
	/*height: 300px;*/
	/*padding-bottom: 64px;*/
	/*height: 500px;*/
	/*position: relative;*/
	height: 400px;
	border: 1px solid #d7d7d7;
	box-shadow: 0 0 20px #d7d7d7;
	background-color: #fff;
	position: absolute;
	width: 382px;
	color: #818181;
	margin: 80px auto;
	position: absolute;
	left: 0;
	right: 0;
}

.submit-button {
	display: inline;
}

.reset-button {
	display: inline;
}

.submit-p {
	margin-left: 120px;
	margin-top:20px;
}
</style>
</body>
</html>

登录逻辑处理代码: doLogin.jsp (用jsp实现,没有用servlet), 用户名与密码都正确后跳转到 list.jsp .

<%@ page language="java" import="dao.*,entity.*,java.util.*,java.sql.*"
	contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%
	String users = request.getParameter("username");
	String pass = request.getParameter("pwd");
	boolean flag = false;
	PreparedStatement sql = null;
	ResultSet rs = null;
	Connection conn = null;
%>

<%
	String driver = "com.mysql.jdbc.Driver";
	String url = "jdbc:mysql://127.0.0.1:3306/shop";
	String use = "root";
	String password = "password";
	Class.forName(driver);
	conn = DriverManager.getConnection(url, use, password);
	sql = conn.prepareStatement("select * from user where username=? and password=?");
	sql.setString(1, users);
	sql.setString(2, pass);
	rs = sql.executeQuery();
	if (rs.next()) {
		flag = true;
	}
	rs.close();
	sql.close();
	conn.close();
%>
<!-- 判断是否是正确的登录用户 -->
<%
	if (flag == true) {
%>
<jsp:forward page="list.jsp" />
<%
	} else if (flag == false) {
%>
<script>
	alert("用户名或密码错误,请重新输入");
	window.location = "login.jsp";
</script>

<%
	}
%>

注册界面与上面登录界面类似

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

<html>
<head>
<title>注册</title>
https://cdn.bootcss.com/semantic-ui/2.3.1/semantic.css"
	rel="stylesheet">
</head>
<body>
	<!-- <p1>test!</p1> -->
	<br>
	<br>
	<br>
	<div class="loginpage">
		<br> <br> <br>
		<h2 align="center">请注册</h2>
		<form name=loginForm action="doRegister.jsp" method=post>
			<table align="center">
				<tr>
					<td>用户名:</td>
					<td><div class="ui input focus">
							<input type="text" placeholder="" name=username>
						</div></td>
				</tr>
				<tr>
					<td>密码:</td>
					<td><div class="ui input focus">
							<input type="password" placeholder="" name=pwd>
						</div></td>
				<tr />
				<br>


			</table>
			<div class="submit-p">
				<div class="submit-button">
					<input type="submit" value="register" class="ui primary button" />
				</div>
				<div class="reset-button">
					<input type="reset" value="reset" class="ui button" />
				</div>
			</div>
		</form>

	</div>

	<style>
.loginpage {
	/*height: 300px;*/
	/*padding-bottom: 64px;*/
	/*height: 500px;*/
	/*position: relative;*/
	height: 400px;
	border: 1px solid #d7d7d7;
	box-shadow: 0 0 20px #d7d7d7;
	background-color: #fff;
	position: absolute;
	width: 382px;
	color: #818181;
	margin: 80px auto;
	position: absolute;
	left: 0;
	right: 0;
}

.submit-button {
	display: inline;
}

.reset-button {
	display: inline;
}

.submit-p {
	margin-left: 120px;
	margin-top:20px;
}
</style>
</body>
</html>

注册逻辑处理代码: doRegister.jsp

<%@ page language="java" import="dao.*,entity.*,java.util.*,java.sql.*"
	contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%
		request.setCharacterEncoding("utf-8");
		String users = request.getParameter("username");
		String pass = request.getParameter("pwd");
	%>
	<%
		String driver = "com.mysql.jdbc.Driver";
		String url = "jdbc:mysql://127.0.0.1:3306/shop";
		String use = "root";
		String password = "password";
		Class.forName(driver);
		Connection conn = DriverManager.getConnection(url, use, password);
		PreparedStatement sql = conn.prepareStatement("insert into user(username,password)values(?,?)");
		sql.setString(1, users);
		sql.setString(2, pass);
		int rtn = sql.executeUpdate();
		sql.close();
		conn.close();
	%>
	<script>
		alert("注册成功");
		window.location = "login.jsp";
	</script>
</body>
</html>

定义Dao

BaseDao

dao下BaseDao.java 用于连接数据库

package dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.security.auth.x500.X500Principal;

//import com.mysql.jdbc.Statement;

public class BaseDao {
	Connection conn = null;
	Statement stmt = null;
	ResultSet rs = null;
	Connection con;

	public static Connection getConnection() throws SQLException {
		Connection connection = null;

		try {
			Class.forName("com.mysql.jdbc.Driver");
			String url = "jdbc:mysql://localhost:3306/shop";
			connection = DriverManager.getConnection(url,"root","password");
		} catch (ClassNotFoundException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return connection;
	}

	public static void closeAll(Connection conn, Statement stmt, ResultSet rs) {
		try {
			if (rs != null)
				rs.close();
			if (stmt != null)
				stmt.close();
			if (conn != null)
				conn.close();
		} catch (SQLException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

}

ProductDaoImp

ProductDaoImp.java用于查询商品,实现了商品查询的两个方法,

  • 一种是findAll()用于商品列表页面 list.jsp
  • 一种是findById()用于商品详情页面 detail.jsp
package dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import org.apache.tomcat.jni.Proc;
//import java.sql.*;
import org.omg.CORBA.PUBLIC_MEMBER;

import com.sun.org.apache.regexp.internal.recompile;

import entity.Product;
import jdk.internal.org.objectweb.asm.commons.StaticInitMerger;

//操作产品的实现类
public class ProductDaoImp {
	/* 作用,按照条件查询产品 */
	public ArrayList findAll() {

		ArrayList list = new ArrayList();
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		try {
			// 1.打开数据库连接
			conn = BaseDao.getConnection();

			// 2.创建执行sql语句对象
			stmt = conn.createStatement();

			// 3.发送sql语句到mysql
			String sql = "select * from product";
			rs = stmt.executeQuery(sql);
			// rs结果集--->遍历--->封装product--->放入ArrayList
			
			while (rs.next())// 循环一次只代表一行
			{
				Product p = new Product();
				p.setId(rs.getInt("id"));
				p.setName(rs.getString("name"));
				p.setImg(rs.getString("img"));
				p.setDesc(rs.getString("desc"));
				p.setNum(rs.getInt("num"));
				p.setPrice(rs.getDouble("price"));
				System.out.println(p.getName());
				list.add(p);
			}
			// 4.
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			BaseDao.closeAll(conn, (com.mysql.jdbc.Statement) stmt, rs);
		}
		return list;
	}
	
	public Product findById(int id) {

		//ArrayList list = new ArrayList();
		Product p = new Product();
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		try {
			// 1.打开数据库连接
			conn = BaseDao.getConnection();

			// 2.创建执行sql语句对象
			stmt = conn.createStatement();

			// 3.发送sql语句到mysql
			String sql = "select * from product where id =" + id;
			rs = stmt.executeQuery(sql);
			// rs结果集--->遍历--->封装product--->放入ArrayList
			
			while (rs.next())// 循环一次只代表一行
			{
				//Product p = new Product();
				p.setId(rs.getInt("id"));
				p.setName(rs.getString("name"));
				p.setImg(rs.getString("img"));
				p.setDesc(rs.getString("desc"));
				p.setNum(rs.getInt("num"));
				p.setPrice(rs.getDouble("price"));
				//System.out.println(p.getName());
				//list.add(p);
			}
			// 4.
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			BaseDao.closeAll(conn, (com.mysql.jdbc.Statement) stmt, rs);
		}
		return p;
	}
//	public static void main(String[] args)throws Throwable{
//		new ProductDaoImp().findAll();
//	}

}

定义Entity

Product

实体类Product.java,定义商品的基本属性.

package entity;

import sun.nio.cs.ext.DoubleByteEncoder;

public class Product {
	private int id;
	private String name;
	private double price;
	private String desc;
	private String img;
	private int num;
	

	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}


	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 double getPrice() {
		return price;
	}


	public void setPrice(double price) {
		this.price = price;
	}


	public String getDesc() {
		return desc;
	}


	public void setDesc(String desc) {
		this.desc = desc;
	}


	public String getImg() {
		return img;
	}


	public void setImg(String img) {
		this.img = img;
	}


	public int getNum() {
		return num;
	}


	public void setNum(int num) {
		this.num = num;
	}

}

CartItem

CartItem 定义购物车对象, 里面包括 商品对象 以及 商品数目;

package entity;

public class CartItem {
	private  Product p;
	private  int  sum;
	
	public Product getP() {
		return p;
	}
	public void setP(Product p) {
		this.p = p;
	}
	public int getSum() {
		return sum;
	}
	public void setSum(int sum) {
		this.sum = sum;
	}
}

商品列表与详情界面

商品列表界面核心代码 list.jsp

<% 
ProductDaoImp dao = new ProductDaoImp();
ArrayList list = dao.findAll();
for(int i=0;i<list.size();i++){ 
    Product p = (Product)list.get(i);
%>

    <li>
    <a href="detail.jsp?id=<%= p.getId() %>">
        <div class="i-pic limit">
            <img src="images/small-<%= p.getImg() %>" />                                            
            <p class="title fl"><%= p.getName() %></p>
            <p class="price fl">
                <b>¥</b>
                <strong><%= p.getPrice() %></strong>
            </p>
            <p class="number fl">
                销量<span><%= p.getNum() %></span>
            </p>
        </div>
        </a>
    </li>
    
<%
}
%>

detail界面核心代码 detail.jsp

<% 
String idStr = request.getParameter("id");
if("".equals(idStr) || idStr == null){
    response.sendRedirect("login.jsp");
}else{
    

int id = Integer.parseInt(request.getParameter("id"));
ProductDaoImp dao = new ProductDaoImp();
Product p = dao.findById(id);
%>

......
......省略(用渲染p的各个属性)
......

<%
}
%>

★购物车页面

detail.jsp和cart.jsp页面之间跳转通过doCart.jsp来连接
doCart.jsp (将商品添加到购物车的逻辑)

{
	"商品id":"cartItem"
}
<%@ page language="java" import="dao.*,entity.*,java.util.*"
	contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
	// 1.获得购物车 Map
	// getAttribute的返回值类型是Object,需要向下转型,
	// 转成你的userName类型的,简单说就是存什么,取出来还是什么.
	HashMap map = (HashMap) session.getAttribute("cart");

	// 2.判断购物车 Map是否存在,不存在则创建
	if (map == null) {
		map = new HashMap();
	}
	// 3.把产品添加到购物车
	// 3.1 根据 id 查询商品
	String id = request.getParameter("id");
	ProductDaoImp dao = new ProductDaoImp();
	Product p = dao.findById(Integer.parseInt(id));
	// 3.2判断 Map 中是否由此商品 , 注意这里id不加引号
	CartItem cartItem = (CartItem) map.get(id);
	// 有--> 把数量+1
	// 无--> 把商品放入购物车 数量设置为1
	if (cartItem != null) {
		cartItem.setSum(cartItem.getSum() + 1);
	} else {
		cartItem = new CartItem();
		cartItem.setP(p); // 关键步骤
		cartItem.setSum(1);
	}
	// 3.3 将产品加入map集合,id+""拼接成字符串型
	map.put(id, cartItem);
	// out.print(map.size());
	// 4.把集合存储到session作用域
	session.setAttribute("cart", map);
	response.sendRedirect("cart.jsp");
%>

遍历map, 前端显示购物车商品

<%
HashMap map = (HashMap)session.getAttribute("cart");
Iterator it = map.keySet().iterator();
while(it.hasNext()){
    Object key = it.next();
    CartItem cartItem = (CartItem)map.get(key);
    Product p = cartItem.getP();
    int sum = cartItem.getSum();

%>
......
<%
}
%>

用于增删商品数量的js代码

<script>
function fun1(id, price) {
    var sum = parseInt(document.getElementById("sum" + id).value) + 1;
    var m = sum * parseFloat(price);
    document.getElementById("m" + id).innerHTML = m;
    document.getElementById("J_Total").innerHTML = m;
    var sum1 = parseInt(document.getElementsByClassName("text_box")[0].value) + 1;
    document.getElementById("J_SelectedItemsCount").innerHTML = sum1;

}

function fun2(id, price) {
    var sum = parseInt(document.getElementById("sum" + id).value) - 1;
    var m = sum * parseFloat(price);
    document.getElementById("m" + id).innerHTML = m;
    document.getElementById("J_Total").innerHTML = m;

    document.getElementById("J_SelectedItemsCount").innerHTML = document.getElementsByClassName("text_box")[0].value;

}
</script>

更多

看参考

servlet+jsp实现小小购物车功能
https://blog.csdn.net/freshbin000/article/details/52348754/

  • 89
    点赞
  • 530
    收藏
  • 打赏
    打赏
  • 76
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:精致技术 设计师:CSDN官方博客 返回首页
评论 76

打赏作者

Co_zy

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

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

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

打赏作者

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

抵扣说明:

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

余额充值