请基于JSP + Servlet + JavaBean + JDBC+MYsql 使用Myeclipse软件,制作一个商品查询项目,根据可以用户输入的商品号从数据库中查询该商品信息和查询所有商品信息 遵循MVC设计模式,其中视图有queryProduct.jsp、displayProduct.jsp、displayAllProduct.jsp和error.jsp几个页面,Product类实现模型,QueryProductServlet类实现控制器。数据库表为products。请具体代码和步骤
时间: 2024-03-11 16:50:06 浏览: 90
好的,以下是具体的代码和步骤:
1. 创建数据库和表
首先需要在MySQL中创建一个名为“test”的数据库,然后在该数据库中创建一个名为“products”的表,表结构如下:
```
CREATE TABLE `products` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`price` double NOT NULL,
`description` varchar(200) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
```
2. 创建JavaBean
创建一个名为“Product”的JavaBean,包含id、name、price和description四个属性,以及对应的getters和setters方法。
```
public class Product {
private int id;
private String name;
private double price;
private String description;
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 getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
```
3. 创建查询逻辑
创建一个名为“QueryProductServlet”的Servlet,实现商品查询的逻辑。
```
public class QueryProductServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String QUERY_PRODUCT = "queryProduct.jsp";
private static final String DISPLAY_PRODUCT = "displayProduct.jsp";
private static final String DISPLAY_ALL_PRODUCT = "displayAllProduct.jsp";
private static final String ERROR = "error.jsp";
private ProductDao productDao = new ProductDao();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String forward = "";
String productId = request.getParameter("productId");
if (productId == null || productId.isEmpty()) {
forward = QUERY_PRODUCT;
} else {
try {
int id = Integer.parseInt(productId);
Product product = productDao.getProductById(id);
if (product != null) {
request.setAttribute("product", product);
forward = DISPLAY_PRODUCT;
} else {
request.setAttribute("error", "Product not found");
forward = ERROR;
}
} catch (NumberFormatException e) {
request.setAttribute("error", "Invalid product ID");
forward = ERROR;
}
}
request.getRequestDispatcher(forward).forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String forward = "";
List<Product> products = productDao.getAllProducts();
if (products != null && !products.isEmpty()) {
request.setAttribute("products", products);
forward = DISPLAY_ALL_PRODUCT;
} else {
request.setAttribute("error", "No products found");
forward = ERROR;
}
request.getRequestDispatcher(forward).forward(request, response);
}
}
```
上面的代码中,QueryProductServlet包含了doGet和doPost两个方法,分别对应用户输入商品号进行单个商品查询和查询所有商品信息的操作。当用户输入商品号时,QueryProductServlet会调用ProductDao对象的getProductById方法从数据库中查询商品信息,并将查询结果存入request对象中,最后转发到displayProduct.jsp页面显示查询结果。当用户不输入商品号时,QueryProductServlet会调用ProductDao对象的getAllProducts方法查询所有商品信息,并将查询结果存入request对象中,最后转发到displayAllProduct.jsp页面显示查询结果。
4. 创建数据访问对象
创建一个名为“ProductDao”的类,实现对产品数据的访问操作。
```
public class ProductDao {
private static final String SELECT_PRODUCT_BY_ID = "SELECT * FROM products WHERE id = ?";
private static final String SELECT_ALL_PRODUCTS = "SELECT * FROM products";
public Product getProductById(int productId) {
Product product = null;
try (Connection conn = getConnection();
PreparedStatement stmt = conn.prepareStatement(SELECT_PRODUCT_BY_ID)) {
stmt.setInt(1, productId);
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
product = new Product();
product.setId(rs.getInt("id"));
product.setName(rs.getString("name"));
product.setPrice(rs.getDouble("price"));
product.setDescription(rs.getString("description"));
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return product;
}
public List<Product> getAllProducts() {
List<Product> products = new ArrayList<>();
try (Connection conn = getConnection();
PreparedStatement stmt = conn.prepareStatement(SELECT_ALL_PRODUCTS);
ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
Product product = new Product();
product.setId(rs.getInt("id"));
product.setName(rs.getString("name"));
product.setPrice(rs.getDouble("price"));
product.setDescription(rs.getString("description"));
products.add(product);
}
} catch (SQLException e) {
e.printStackTrace();
}
return products;
}
private Connection getConnection() throws SQLException {
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "root";
return DriverManager.getConnection(url, user, password);
}
}
```
上面的代码中,ProductDao类包含了getProductById和getAllProducts两个方法,分别对应单个商品查询和查询所有商品信息的操作。在getProductById方法中,使用了PreparedStatement对象执行SQL查询,并将查询结果封装成Product对象返回。在getAllProducts方法中,使用了PreparedStatement对象执行SQL查询,并将查询结果封装成List<Product>返回。
5. 创建JSP页面
创建一个名为“queryProduct.jsp”的JSP页面,用于用户输入商品号进行单个商品查询。
```
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Query Product</title>
</head>
<body>
<h1>Query Product</h1>
<form method="get" action="QueryProductServlet">
<label>Product ID:</label>
<input type="text" name="productId"><br>
<input type="submit" value="Query">
</form>
</body>
</html>
```
创建一个名为“displayProduct.jsp”的JSP页面,用于显示单个商品查询的结果。
```
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Display Product</title>
</head>
<body>
<h1>Display Product</h1>
<table border="1" cellpadding="5">
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
<th>Description</th>
</tr>
<c:if test="${not empty product}">
<tr>
<td>${product.id}</td>
<td>${product.name}</td>
<td>${product.price}</td>
<td>${product.description}</td>
</tr>
</c:if>
</table>
<br>
<a href="queryProduct.jsp">Back to Query Product</a>
</body>
</html>
```
创建一个名为“displayAllProduct.jsp”的JSP页面,用于显示所有商品信息的查询结果。
```
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Display All Products</title>
</head>
<body>
<h1>Display All Products</h1>
<table border="1" cellpadding="5">
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
<th>Description</th>
</tr>
<c:forEach items="${products}" var="product">
<tr>
<td>${product.id}</td>
<td>${product.name}</td>
<td>${product.price}</td>
<td>${product.description}</td>
</tr>
</c:forEach>
</table>
<br>
<a href="queryProduct.jsp">Back to Query Product</a>
</body>
</html>
```
创建一个名为“error.jsp”的JSP页面,用于显示错误信息。
```
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Error</title>
</head>
<body>
<h1>Error</h1>
<p>${error}</p>
<br>
<a href="queryProduct.jsp">Back to Query Product</a>
</body>
</html>
```
6. 部署应用程序
将所有代码文件放入MyEclipse中的Web项目中,并将MySQL驱动程序(mysql-connector-java-5.1.46.jar)放入Web项目的WebContent/WEB-INF/lib目录中。最后,将Web项目部署到Tomcat服务器中。
7. 测试应用程序
在浏览器中访问http://localhost:8080/yourWebContext/queryProduct.jsp,输入商品号进行单个商品查询,或者直接点击“Query All Products”按钮查询所有商品信息。
阅读全文