给出能实现文档内容功能的完整代码
时间: 2024-12-23 20:14:34 浏览: 10
实现文档中描述的功能需要多个JSP页面和Java Servlet来处理请求。以下是一个简化的示例代码,展示了如何实现这些功能。请注意,这只是一个基本的示例,实际应用中可能需要更多的安全性和错误处理措施。
### 数据库配置
首先,确保你有一个MySQL数据库,并创建一个名为`mydb`的数据库,然后创建两个表:`users`和`products`。
```sql
CREATE DATABASE mydb;
USE mydb;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(50) NOT NULL,
role ENUM('admin', 'user') DEFAULT 'user'
);
CREATE TABLE products (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
price DECIMAL(10, 2) NOT NULL,
description TEXT
);
```
### 注册页面 (register.jsp)
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Register</title>
</head>
<body>
<h2>Register</h2>
<form action="RegisterServlet" method="post">
Username: <input type="text" name="username" required><br>
Password: <input type="password" name="password" required><br>
<input type="submit" value="Register">
</form>
</body>
</html>
```
### 注册Servlet (RegisterServlet.java)
```java
import java.io.IOException;
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 java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "your_password");
PreparedStatement pstmt = conn.prepareStatement("INSERT INTO users (username, password) VALUES (?, ?)");
pstmt.setString(1, username);
pstmt.setString(2, password);
pstmt.executeUpdate();
response.sendRedirect("login1.jsp");
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
### 登录页面 (login1.jsp)
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<h2>Login</h2>
<form action="LoginServlet" method="post">
Username: <input type="text" name="username" required><br>
Password: <input type="password" name="password" required><br>
<input type="submit" value="Login">
</form>
</body>
</html>
```
### 登录Servlet (LoginServlet.java)
```java
import java.io.IOException;
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 java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "your_password");
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM users WHERE username = ? AND password = ?");
pstmt.setString(1, username);
pstmt.setString(2, password);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
String role = rs.getString("role");
if ("admin".equals(role)) {
response.sendRedirect("shopadmin.jsp");
} else {
response.sendRedirect("shoplist.jsp");
}
} else {
response.sendRedirect("login1.jsp?error=Invalid credentials");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
### 商品管理页面 (shopadmin.jsp)
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Shop Admin</title>
</head>
<body>
<h2>Add Product</h2>
<form action="AddProductServlet" method="post">
Name: <input type="text" name="name" required><br>
Price: <input type="number" step="0.01" name="price" required><br>
Description: <textarea name="description"></textarea><br>
<input type="submit" value="Add Product">
</form>
<h2>Products List</h2>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
<th>Description</th>
</tr>
<%
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "your_password");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM products");
while (rs.next()) {
%>
<tr>
<td><%= rs.getInt("id") %></td>
<td><%= rs.getString("name") %></td>
<td><%= rs.getBigDecimal("price") %></td>
<td><%= rs.getString("description") %></td>
</tr>
<%
}
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
</table>
</body>
</html>
```
### 添加商品Servlet (AddProductServlet.java)
```java
import java.io.IOException;
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 java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
@WebServlet("/AddProductServlet")
public class AddProductServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
double price = Double.parseDouble(request.getParameter("price"));
String description = request.getParameter("description");
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "your_password");
PreparedStatement pstmt = conn.prepareStatement("INSERT INTO products (name, price, description) VALUES (?, ?, ?)");
pstmt.setString(1, name);
pstmt.setDouble(2, price);
pstmt.setString(3, description);
pstmt.executeUpdate();
response.sendRedirect("shopadmin.jsp");
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
### 商品列表页面 (shoplist.jsp)
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Shop List</title>
</head>
<body>
<h2>Products List</h2>
<table border="1">
<tr>
<th>Name</th>
<th>Price</th>
<th>Description</th>
<th>Action</th>
</tr>
<%
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "your_password");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM products");
while (rs.next()) {
%>
<tr>
<td><%= rs.getString("name") %></td>
<td><%= rs.getBigDecimal("price") %></td>
<td><%= rs.getString("description") %></td>
<td><a href="shopdetail.jsp?id=<%= rs.getInt("id") %>">View Details</a></td>
</tr>
<%
}
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
</table>
</body>
</html>
```
### 商品详情页面 (shopdetail.jsp)
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Product Detail</title>
</head>
<body>
<%
int id = Integer.parseInt(request.getParameter("id"));
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "your_password");
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM products WHERE id = ?");
pstmt.setInt(1, id);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
%>
<h2><%= rs.getString("name") %></h2>
<p>Price: <%= rs.getBigDecimal("price") %></p>
<p>Description: <%= rs.getString("description") %></p>
<form action="AddToCartServlet" method="post">
Quantity: <input type="number" name="quantity" min="1" value="1"><br>
<input type="hidden" name="productId" value="<%= id %>">
<input type="submit" value="Add to Cart">
</form>
<%
}
rs.close();
pstmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
</body>
</html>
```
### 添加到购物车Servlet (AddToCartServlet.java)
```java
import java.io.IOException;
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("/AddToCartServlet")
public class AddToCartServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
String username = (String) session.getAttribute("username");
if (username == null) {
response.sendRedirect("login1.jsp");
return;
}
int productId = Integer.parseInt(request.getParameter("productId"));
int quantity = Integer.parseInt(request.getParameter("quantity"));
// Store the cart items in session
CartItem item = new CartItem(productId, quantity);
Cart cart = (Cart) session.getAttribute("cart");
if (cart == null) {
cart = new Cart();
session.setAttribute("cart", cart);
}
cart.addItem(item);
response.sendRedirect("shopcart.jsp");
}
}
class CartItem {
private int productId;
private int quantity;
public CartItem(int productId, int quantity) {
this.productId = productId;
this.quantity = quantity;
}
public int getProductId() {
return productId;
}
public int getQuantity() {
return quantity;
}
}
class Cart {
private List<CartItem> items = new ArrayList<>();
public void addItem(CartItem item) {
items.add(item);
}
public List<CartItem> getItems() {
return items;
}
}
```
### 购物车页面 (shopcart.jsp)
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.util.List" %>
<%@ page import="javax.servlet.http.HttpSession" %>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Shopping Cart</title>
</head>
<body>
<h2>Shopping Cart</h2>
<%
HttpSession session = request.getSession();
String username = (String) session.getAttribute("username");
if (username == null) {
response.sendRedirect("login1.jsp");
return;
}
Cart cart = (Cart) session.getAttribute("cart");
if (cart != null && !cart.getItems().isEmpty()) {
%>
<table border="1">
<tr>
<th>Name</th>
<th>Price</th>
<th>Quantity</th>
<th>Total</th>
<th>Action</th>
</tr>
<%
double total = 0;
for (CartItem item : cart.getItems()) {
int productId = item.getProductId();
int quantity = item.getQuantity();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "your_password");
PreparedStatement pstmt =
阅读全文