JSP(JavaServer Pages)是一种用于创建动态Web页面的技术,它允许在HTML或XML文档中嵌入Java代码片段和表达式。下面是一个简单的JSP商品显示功能的示例代码,包括数据库连接、查询和结果展示。
db.url=jdbc:mysql://localhost:3306/your_database
db.username=your_username
db.password=your_password
<%@ page import="java.sql.*" %>
<%@ page import="java.util.Properties" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>商品列表</title>
</head>
<body>
<h1>商品列表</h1>
<table border="1">
<tr>
<th>ID</th>
<th>名称</th>
<th>价格</th>
</tr>
<%
// 加载数据库驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 读取数据库配置
Properties props = new Properties();
props.load(getServletContext().getResourceAsStream("/WEB-INF/db.properties"));
String url = props.getProperty("db.url");
String username = props.getProperty("db.username");
String password = props.getProperty("db.password");
// 连接数据库
try (Connection conn = DriverManager.getConnection(url, username, password)) {
String sql = "SELECT id, name, price FROM products";
try (Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
double price = rs.getDouble("price");
%>
<tr>
<td><%= id %></td>
<td><%= name %></td>
<td><%= price %></td>
</tr>
<%
}
}
} catch (SQLException e) {
e.printStackTrace();
}
%>
</table>
</body>
</html>
原因:可能是数据库URL、用户名或密码错误,或者数据库服务未启动。
解决方法:检查db.properties
文件中的配置信息,确保数据库服务正常运行。
原因:SQL语句可能有误,或者数据库中确实没有数据。 解决方法:在数据库管理工具中手动执行SQL语句,验证其正确性。
原因:字符编码设置不正确。
解决方法:在JSP页面头部添加<%@ page contentType="text/html;charset=UTF-8" language="java" %>
确保字符编码一致。
通过以上代码和解释,你应该能够理解如何在JSP中实现商品显示功能,并解决一些常见问题。
领取专属 10元无门槛券
手把手带您无忧上云