用eclipse从0开始用java写一个网上购物商城系统

时间: 2024-05-13 22:14:47 浏览: 13
建立一个Java Web项目 1. 打开Eclipse,选择File -> New -> Dynamic Web Project。 2. 输入项目名称,选择Target runtime,然后点击Next。 3. 选择Web Module版本号,然后点击Next。 4. 选择Java版本号,然后点击Next。 5. 输入Source folder名称,然后点击Next。 6. 点击Finish。 创建数据库 1. 在Eclipse中打开Database Development视图。 2. 在Database Development视图中,右键点击Database Connections,选择New。 3. 输入数据库连接信息,点击Test Connection确认连接是否成功,然后点击OK。 4. 在Database Development视图中,右键点击已连接的数据库,选择New SQL Scrapbook。 5. 在SQL Scrapbook中输入以下SQL代码: ```sql CREATE DATABASE shopping_mall; USE shopping_mall; CREATE TABLE users ( id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, username VARCHAR(50) NOT NULL, password VARCHAR(50) NOT NULL, email VARCHAR(50) NOT NULL, phone VARCHAR(50) NOT NULL ); CREATE TABLE products ( id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50) NOT NULL, price DOUBLE NOT NULL, details VARCHAR(500) NOT NULL, image VARCHAR(100) NOT NULL ); CREATE TABLE orders ( id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, user_id INT(11) NOT NULL, product_id INT(11) NOT NULL, quantity INT(11) NOT NULL, price DOUBLE NOT NULL, order_date DATETIME DEFAULT CURRENT_TIMESTAMP ); ``` 6. 点击Run SQL执行SQL代码,创建数据库和表格。 创建Java Bean 1. 在src目录下创建一个名为com.shoppingmall的包。 2. 在com.shoppingmall包下创建一个名为User的Java类,并添加以下代码: ```java package com.shoppingmall; public class User { private int id; private String username; private String password; private String email; private String phone; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } 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 getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } } ``` 3. 在com.shoppingmall包下创建一个名为Product的Java类,并添加以下代码: ```java package com.shoppingmall; public class Product { private int id; private String name; private double price; private String details; private String image; 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 getDetails() { return details; } public void setDetails(String details) { this.details = details; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } } ``` 创建DAO类 1. 在com.shoppingmall包下创建一个名为UserDAO的Java类,并添加以下代码: ```java package com.shoppingmall; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; public class UserDAO { private Connection connection; public UserDAO(Connection connection) { this.connection = connection; } public boolean createUser(User user) { boolean success = false; try { String sql = "INSERT INTO users (username, password, email, phone) VALUES (?, ?, ?, ?)"; PreparedStatement statement = connection.prepareStatement(sql); statement.setString(1, user.getUsername()); statement.setString(2, user.getPassword()); statement.setString(3, user.getEmail()); statement.setString(4, user.getPhone()); int result = statement.executeUpdate(); if (result > 0) { success = true; } } catch (SQLException e) { e.printStackTrace(); } return success; } public User getUserById(int id) { User user = null; try { String sql = "SELECT * FROM users WHERE id=?"; PreparedStatement statement = connection.prepareStatement(sql); statement.setInt(1, id); ResultSet rs = statement.executeQuery(); if (rs.next()) { user = new User(); user.setId(rs.getInt("id")); user.setUsername(rs.getString("username")); user.setEmail(rs.getString("email")); user.setPhone(rs.getString("phone")); } } catch (SQLException e) { e.printStackTrace(); } return user; } public User getUserByUsernameAndPassword(String username, String password) { User user = null; try { String sql = "SELECT * FROM users WHERE username=? AND password=?"; PreparedStatement statement = connection.prepareStatement(sql); statement.setString(1, username); statement.setString(2, password); ResultSet rs = statement.executeQuery(); if (rs.next()) { user = new User(); user.setId(rs.getInt("id")); user.setUsername(rs.getString("username")); user.setEmail(rs.getString("email")); user.setPhone(rs.getString("phone")); } } catch (SQLException e) { e.printStackTrace(); } return user; } public ArrayList<User> getAllUsers() { ArrayList<User> users = new ArrayList<>(); try { String sql = "SELECT * FROM users"; PreparedStatement statement = connection.prepareStatement(sql); ResultSet rs = statement.executeQuery(); while (rs.next()) { User user = new User(); user.setId(rs.getInt("id")); user.setUsername(rs.getString("username")); user.setEmail(rs.getString("email")); user.setPhone(rs.getString("phone")); users.add(user); } } catch (SQLException e) { e.printStackTrace(); } return users; } } ``` 2. 在com.shoppingmall包下创建一个名为ProductDAO的Java类,并添加以下代码: ```java package com.shoppingmall; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; public class ProductDAO { private Connection connection; public ProductDAO(Connection connection) { this.connection = connection; } public boolean createProduct(Product product) { boolean success = false; try { String sql = "INSERT INTO products (name, price, details, image) VALUES (?, ?, ?, ?)"; PreparedStatement statement = connection.prepareStatement(sql); statement.setString(1, product.getName()); statement.setDouble(2, product.getPrice()); statement.setString(3, product.getDetails()); statement.setString(4, product.getImage()); int result = statement.executeUpdate(); if (result > 0) { success = true; } } catch (SQLException e) { e.printStackTrace(); } return success; } public Product getProductById(int id) { Product product = null; try { String sql = "SELECT * FROM products WHERE id=?"; PreparedStatement statement = connection.prepareStatement(sql); statement.setInt(1, id); ResultSet rs = statement.executeQuery(); if (rs.next()) { product = new Product(); product.setId(rs.getInt("id")); product.setName(rs.getString("name")); product.setPrice(rs.getDouble("price")); product.setDetails(rs.getString("details")); product.setImage(rs.getString("image")); } } catch (SQLException e) { e.printStackTrace(); } return product; } public ArrayList<Product> getAllProducts() { ArrayList<Product> products = new ArrayList<>(); try { String sql = "SELECT * FROM products"; PreparedStatement statement = connection.prepareStatement(sql); ResultSet rs = statement.executeQuery(); while (rs.next()) { Product product = new Product(); product.setId(rs.getInt("id")); product.setName(rs.getString("name")); product.setPrice(rs.getDouble("price")); product.setDetails(rs.getString("details")); product.setImage(rs.getString("image")); products.add(product); } } catch (SQLException e) { e.printStackTrace(); } return products; } } ``` 创建Servlet类 1. 在src目录下创建一个名为com.shoppingmall.servlet的包。 2. 在com.shoppingmall.servlet包下创建一个名为UserServlet的Java类,并添加以下代码: ```java package com.shoppingmall.servlet; import java.io.IOException; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.shoppingmall.User; import com.shoppingmall.UserDAO; public class UserServlet extends HttpServlet { private static final long serialVersionUID = 1L; private UserDAO userDAO; public void init() { userDAO = new UserDAO((Connection) getServletContext().getAttribute("dbConnection")); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ArrayList<User> users = userDAO.getAllUsers(); request.setAttribute("users", users); request.getRequestDispatcher("/user.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String password = request.getParameter("password"); String email = request.getParameter("email"); String phone = request.getParameter("phone"); User user = new User(); user.setUsername(username); user.setPassword(password); user.setEmail(email); user.setPhone(phone); boolean success = userDAO.createUser(user); if (success) { response.sendRedirect(request.getContextPath() + "/user"); } else { response.sendRedirect(request.getContextPath() + "/error.jsp"); } } } ``` 3. 在com.shoppingmall.servlet包下创建一个名为ProductServlet的Java类,并添加以下代码: ```java package com.shoppingmall.servlet; import java.io.IOException; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.shoppingmall.Product; import com.shoppingmall.ProductDAO; public class ProductServlet extends HttpServlet { private static final long serialVersionUID = 1L; private ProductDAO productDAO; public void init() { productDAO = new ProductDAO((Connection) getServletContext().getAttribute("dbConnection")); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ArrayList<Product> products = productDAO.getAllProducts(); request.setAttribute("products", products); request.getRequestDispatcher("/product.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("name"); double price = Double.parseDouble(request.getParameter("price")); String details = request.getParameter("details"); String image = request.getParameter("image"); Product product = new Product(); product.setName(name); product.setPrice(price); product.setDetails(details); product.setImage(image); boolean success = productDAO.createProduct(product); if (success) { response.sendRedirect(request.getContextPath() + "/product"); } else { response.sendRedirect(request.getContextPath() + "/error.jsp"); } } } ``` 创建JSP页面 1. 在WebContent目录下创建一个名为user.jsp的JSP页面,并添加以下代码: ```jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>User List</title> </head> <body> <h1>User List</h1> <table border="1"> <tr> <th>ID</th> <th>Username</th> <th>Email</th> <th>Phone</th> </tr> <c:forEach items="${users}" var="user"> <tr> <td>${user.id}</td> <td>${user.username}</td> <td>${user.email}</td> <td>${user.phone}</td> </tr> </c:forEach> </table> <h1>Create User</h1> <form action="${pageContext.request.contextPath}/user" method="POST"> <label>Username:</label> <input type="text" name="username"><br> <label>Password:</label> <input type="password" name="password"><br> <label>Email:</label> <input type="email" name="email"><br> <label>Phone:</label> <input type="text" name="phone"><br> <input type="submit" value="Create"> </form> </body> </html> ``` 2. 在WebContent目录下创建一个名为product.jsp的JSP页面,并添加以下代码: ```jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Product List</title> </head> <body> <h1>Product List</h1> <table border="1"> <tr> <th>ID</th> <th>Name</th> <th>Price</th> <th>Details</th> <th>Image</th> </tr> <c:forEach items="${products}" var="product"> <tr> <td>${product.id}</td> <td>${product.name}</td> <td>${product.price}</td> <td>${product.details}</td> <td>${product.image}</td> </tr> </c:forEach> </table> <h1>Create Product</h1> <form action="${pageContext.request.contextPath}/product" method="POST"> <label>Name:</label> <input type="text" name="name"><br> <label>Price:</label> <input type="number" name="price"><br> <label>Details:</label> <textarea name="details"></textarea><br> <label>Image:</label> <input type="text" name="image"><br> <input type="submit" value="Create"> </form> </body> </html> ``` 运行项目 1. 在Eclipse中,右键点击项目名称,选择Run As -> Run on Server。 2. 选择服务器,点击Finish。 3. 在浏览器中输入http://localhost:8080/项目名称/user和http://localhost:8080/项目名称/product,即可访问User List和Product List页面,可以创建新的用户和商品。

相关推荐

最新推荐

recommend-type

网上购物系统文档 eclipse+tomcat+struts

Java实训时的文档,用三种方法完成:servlet、Jsp、struts。只要做登录及注册界面,但是文档是可以通用的把!呵呵呵~~~
recommend-type

使用eclipse创建第一个servlet程序.docx

小白入门专属教程,手把手教你如何用eclipse创建servlet程序,附带简述和介绍,非常详细,图文教程,每一步都有讲解,有手就行。
recommend-type

用Eclipse开发Java的使用方法

http://hi.baidu.com/php_2008/blog/item/4cb0e7c49fe497af8326ac36.html
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

MATLAB柱状图在信号处理中的应用:可视化信号特征和频谱分析

![matlab画柱状图](https://img-blog.csdnimg.cn/3f32348f1c9c4481a6f5931993732f97.png) # 1. MATLAB柱状图概述** MATLAB柱状图是一种图形化工具,用于可视化数据中不同类别或组的分布情况。它通过绘制垂直条形来表示每个类别或组中的数据值。柱状图在信号处理中广泛用于可视化信号特征和进行频谱分析。 柱状图的优点在于其简单易懂,能够直观地展示数据分布。在信号处理中,柱状图可以帮助工程师识别信号中的模式、趋势和异常情况,从而为信号分析和处理提供有价值的见解。 # 2. 柱状图在信号处理中的应用 柱状图在信号处理
recommend-type

用Spring boot和vue写一个登录注册界面

好的,这是一个比较常见的技术问题,我可以为您提供一些参考资料和思路。首先,您可以使用Spring Boot作为后端框架来处理用户认证和注册的逻辑,比如使用Spring Security实现用户登录认证。同时,您还需要设计相应的数据模型和数据库表结构来存储用户信息。在前端方面,您可以使用Vue.js作为框架来构建登录注册页面,使用Axios来发起API请求并和后端进行交互。当然,在实现过程中,还需要考虑一些具体细节,比如数据校验、安全性和用户体验等方面。希望这些信息能够帮助到您。
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。
recommend-type

"互动学习:行动中的多样性与论文攻读经历"

多样性她- 事实上SCI NCES你的时间表ECOLEDO C Tora SC和NCESPOUR l’Ingén学习互动,互动学习以行动为中心的强化学习学会互动,互动学习,以行动为中心的强化学习计算机科学博士论文于2021年9月28日在Villeneuve d'Asq公开支持马修·瑟林评审团主席法布里斯·勒菲弗尔阿维尼翁大学教授论文指导奥利维尔·皮耶昆谷歌研究教授:智囊团论文联合主任菲利普·普雷教授,大学。里尔/CRISTAL/因里亚报告员奥利维耶·西格德索邦大学报告员卢多维奇·德诺耶教授,Facebook /索邦大学审查员越南圣迈IMT Atlantic高级讲师邀请弗洛里安·斯特鲁布博士,Deepmind对于那些及时看到自己错误的人...3谢谢你首先,我要感谢我的两位博士生导师Olivier和Philippe。奥利维尔,"站在巨人的肩膀上"这句话对你来说完全有意义了。从科学上讲,你知道在这篇论文的(许多)错误中,你是我可以依
recommend-type

MATLAB柱状图在数据分析中的作用:从可视化到洞察

![MATLAB柱状图在数据分析中的作用:从可视化到洞察](https://img-blog.csdnimg.cn/img_convert/1a36558cefc0339f7836cca7680c0aef.png) # 1. MATLAB柱状图概述** 柱状图是一种广泛用于数据可视化的图表类型,它使用垂直条形来表示数据中不同类别或组别的值。在MATLAB中,柱状图通过`bar`函数创建,该函数接受数据向量或矩阵作为输入,并生成相应的高度条形。 柱状图的优点在于其简单性和易于理解性。它们可以快速有效地传达数据分布和组别之间的比较。此外,MATLAB提供了广泛的定制选项,允许用户调整条形颜色、