商品展示的JSP(JavaServer Pages)代码通常用于在网页上动态展示商品信息。以下是一个简单的示例,展示了如何使用JSP来显示商品列表。
JSP是一种服务器端技术,允许开发者将Java代码嵌入到HTML页面中,从而实现动态网页内容的生成。JSP页面在服务器上被编译成Servlet,然后执行并生成HTML响应。
public class Product {
private int id;
private String name;
private double price;
public Product(int id, String name, double price) {
this.id = id;
this.name = name;
this.price = price;
}
// Getters and Setters
public int getId() { return id; }
public String getName() { return name; }
public double getPrice() { return price; }
}
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/products")
public class ProductServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Product> products = new ArrayList<>();
products.add(new Product(1, "Laptop", 999.99));
products.add(new Product(2, "Smartphone", 799.99));
products.add(new Product(3, "Tablet", 399.99));
request.setAttribute("products", products);
request.getRequestDispatcher("/productList.jsp").forward(request, response);
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Product List</title>
</head>
<body>
<h1>Product List</h1>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
</tr>
<c:forEach var="product" items="${products}">
<tr>
<td>${product.id}</td>
<td>${product.name}</td>
<td>${product.price}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
通过以上示例和解释,希望能帮助你理解商品展示JSP代码的基础概念、优势、应用场景以及常见问题解决方法。
领取专属 10元无门槛券
手把手带您无忧上云