用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页面,可以创建新的用户和商品。