<tr><td>商品Id:</td><td><input type="text" name="pid" placeholder="商品ID可以不输入"></td> 前端输入商品ID后通过数据库product表精确查询,将查询到的商品id、商品图片、商品价格展示在前端jsp页面的代码
时间: 2023-10-07 21:13:26 浏览: 48
好的,以下是一个简单的实现示例:
前端jsp页面(index.jsp):
```
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>商品查询</title>
</head>
<body>
<h1>商品查询</h1>
<form action="query.jsp" method="post">
<label for="pid">商品ID:</label>
<input type="text" name="pid" id="pid" placeholder="商品ID可以不输入">
<input type="submit" value="查询">
</form>
</body>
</html>
```
后端jsp页面(query.jsp):
```
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page import="java.sql.*" %>
<%@ page import="com.example.Product" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>商品查询结果</title>
</head>
<body>
<h1>商品查询结果</h1>
<%
// 获取用户输入的商品ID
String pid = request.getParameter("pid");
if (pid == null || pid.equals("")) {
// 如果用户没有输入商品ID,则返回错误提示
out.println("<p>请输入商品ID</p>");
} else {
// 如果用户输入了商品ID,则连接数据库执行查询操作
try {
// 加载JDBC驱动
Class.forName("com.mysql.jdbc.Driver");
// 获取数据库连接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");
// 预编译SQL语句
String sql = "SELECT * FROM product WHERE id = ?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, pid);
// 执行查询操作
ResultSet rs = stmt.executeQuery();
// 处理查询结果
if (rs.next()) {
Product product = new Product();
product.setId(rs.getString("id"));
product.setImage(rs.getString("image"));
product.setPrice(rs.getDouble("price"));
// 将查询结果保存在JavaBean对象中,传递给jsp页面展示
request.setAttribute("product", product);
// 转发到商品展示页面
request.getRequestDispatcher("/product.jsp").forward(request, response);
} else {
// 如果没有查询到任何结果,则返回错误提示
out.println("<p>未查询到相关商品</p>");
}
// 关闭数据库连接
rs.close();
stmt.close();
conn.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
%>
</body>
</html>
```
商品展示页面(product.jsp):
```
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>商品展示</title>
</head>
<body>
<h1>商品展示</h1>
<c:if test="${not empty product}">
<p>商品ID:${product.id}</p>
<p>商品图片:<img src="${product.image}" alt="商品图片"></p>
<p>商品价格:${product.price}</p>
</c:if>
</body>
</html>
```
需要注意的是,以上示例中使用的是MySQL数据库和JSTL标签库,具体实现可能会因为数据库和框架的不同而有所不同,需要根据具体情况进行调整。