JSP(Java Server Pages)是一种基于Java技术的服务器端编程技术,用于创建动态网页。一个商品管理系统通常包括商品的增删改查、用户管理、订单处理等功能。下面是一个简单的JSP商品管理系统代码示例,包括基本的数据库连接和一些核心功能。
<%@ page import="java.sql.*" %>
<%
String url = "jdbc:mysql://localhost:3306/ecommerce";
String username = "root";
String password = "password";
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, username, password);
%>
<jsp:useBean id="dbConn" class="java.lang.String" scope="page">
<%= conn.toString() %>
</jsp:useBean>
<%
} catch (Exception e) {
e.printStackTrace();
}
%>
<%@ page import="java.sql.*" %>
<%@ include file="DBConnection.jsp" %>
<html>
<head>
<title>商品列表</title>
</head>
<body>
<h1>商品列表</h1>
<table border="1">
<tr>
<th>ID</th>
<th>名称</th>
<th>价格</th>
</tr>
<%
try {
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.getDouble("price") %></td>
</tr>
<%
}
rs.close();
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
%>
</table>
</body>
</html>
<%@ page import="java.sql.*" %>
<%@ include file="DBConnection.jsp" %>
<html>
<head>
<title>添加商品</title>
</head>
<body>
<h1>添加商品</h1>
<form action="AddProductAction.jsp" method="post">
名称: <input type="text" name="name"><br>
价格: <input type="text" name="price"><br>
<input type="submit" value="添加">
</form>
</body>
</html>
<%@ page import="java.sql.*" %>
<%@ include file="DBConnection.jsp" %>
<%
String name = request.getParameter("name");
double price = Double.parseDouble(request.getParameter("price"));
try {
PreparedStatement pstmt = conn.prepareStatement("INSERT INTO products (name, price) VALUES (?, ?)");
pstmt.setString(1, name);
pstmt.setDouble(2, price);
pstmt.executeUpdate();
response.sendRedirect("ProductList.jsp");
} catch (SQLException e) {
e.printStackTrace();
}
%>
PreparedStatement
代替Statement
来防止SQL注入。对于部署此类应用,可以考虑使用具有良好Java支持的云服务平台,如腾讯云的云服务器和云数据库服务,它们提供了稳定且高性能的环境来运行Java Web应用。
希望这些信息对你有所帮助!如果有更具体的问题或需要进一步的帮助,请随时提问。
领取专属 10元无门槛券
手把手带您无忧上云