如何从 servlet 读取 HashMap 值并以 jsp 显示它



>Shooping Servlet

包装公司购物;

import java.io.IOException;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * Servlet implementation class ShoppingServlet
 */
@WebServlet("/ShoppingServlet")
public class ShoppingServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        final Map<Integer,String> products= new HashMap<Integer,String>();
        products.put(1, "Motorola MotoX");
        products.put(2, "Google Pixel2");
        products.put(3, "Essential");
        products.put(4, "Iphone 6");
        request.setAttribute("product", products);
    }
}

浏览.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Click on the products to add to the Cart.
<br/>
<c:forEach items="${product}" var="pro">
    ${pro.value};
    <br/>
</c:forEach>
</body>
</html>

问题是它没有在 jsp 中显示映射值。单击要添加到购物车的产品,但价值丢失。

您可以使用脚本在 jsp 页面上显示它。

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Click on the products to add to the Cart.
<br/> <% for(String key: product.getKeys()){            out.println(product.get(key)+"<br/>");  } %>
</body>
</html>

最新更新