JSP(JavaServer Pages)是一种基于Java技术的服务器端编程技术,用于生成动态网页内容。下面是一个简单的JSP手机商城代码示例,包括商品展示和购物车功能。
JSP允许在HTML页面中嵌入Java代码,通过服务器端的处理生成动态内容。它通常与Servlet一起使用,用于构建Web应用程序。
适用于需要动态生成内容的Web应用,如电子商务网站、论坛、博客等。
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>手机商城</title>
</head>
<body>
<h1>手机商城</h1>
<table border="1">
<tr>
<th>名称</th>
<th>价格</th>
<th>操作</th>
</tr>
<%-- 假设有一个商品列表 --%>
<%
List<Product> products = (List<Product>) request.getAttribute("products");
if (products != null) {
for (Product product : products) {
%>
<tr>
<td><%= product.getName() %></td>
<td><%= product.getPrice() %></td>
<td><a href="addToCart?id=<%= product.getId() %>">加入购物车</a></td>
</tr>
<%
}
}
%>
</table>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>购物车</title>
</head>
<body>
<h1>购物车</h1>
<table border="1">
<tr>
<th>商品名称</th>
<th>价格</th>
<th>数量</th>
<th>小计</th>
</tr>
<%-- 假设有一个购物车列表 --%>
<%
List<CartItem> cartItems = (List<CartItem>) session.getAttribute("cart");
if (cartItems != null) {
for (CartItem item : cartItems) {
%>
<tr>
<td><%= item.getProductName() %></td>
<td><%= item.getPrice() %></td>
<td><%= item.getQuantity() %></td>
<td><%= item.getPrice() * item.getQuantity() %></td>
</tr>
<%
}
}
%>
</table>
</body>
</html>
@WebServlet("/products")
public class ProductServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 模拟商品数据
List<Product> products = Arrays.asList(
new Product(1, "iPhone 12", 6999),
new Product(2, "Samsung Galaxy S21", 5999),
new Product(3, "Xiaomi Mi 11", 3999)
);
request.setAttribute("products", products);
request.getRequestDispatcher("/products.jsp").forward(request, response);
}
}
public class Product {
private int id;
private String name;
private double price;
// 构造函数、getter和setter方法
}
public class CartItem {
private String productName;
private double price;
private int quantity;
// 构造函数、getter和setter方法
}
通过以上代码和说明,你可以构建一个简单的手机商城应用。如果遇到具体问题,可以根据错误信息和日志进一步排查。
领取专属 10元无门槛券
手把手带您无忧上云