【发布时间】:2017-12-01 14:37:36
【问题描述】:
这是我在bean类中的函数——product.java 我从数据库中选择某些细节并将数据库中的值放入哈希图中。 HashMap 是一种类产品。
public HashMap<String,Products> showProducts()
{
HttpServletRequest request = null;
PreparedStatement preparedStatement;
HashMap<String,Products>productMap=new HashMap<String,Products>();
try
{
preparedStatement = con.prepareStatement("select * from productdetails where producttype='toy'");
ResultSet resultSet=preparedStatement.executeQuery();
Products toy=new Products();
while(resultSet.next()){
toy.setProductId(resultSet.getInt(1));
toy.setProductName(resultSet.getString(2));
toy.setProductPrice(resultSet.getInt(3));
productMap.put("toy",toy);
request.setAttribute("productSessionMap",productMap);
}
}
catch(Exception e)
{
e.printStackTrace();
}
return productMap;
}
这是jsp页面
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@page import="java.util.Set"%>
<%@page import="java.util.HashMap"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Welcome!!!! <c:out value="${sessionScope.loginBean.userName}"></c:out>
<jsp:useBean id="loginBean" class="com.training.entity.ShoppingCart"
scope="session"></jsp:useBean>
<jsp:setProperty property="*" name="loginBean"/>
<c:set var="status" value="${loginBean.showProducts()}"></c:set>
<c:set var="keys" value="${status.keySet()}"></c:set>
<c:out value="${status.toString()}"></c:out> <!-- This line displays last value of hashmap-!>
<c:forEach var="type" items="${productSessionMap}">
<c:out value="${type[keys]}"></c:out>
</c:forEach>
</body>
</html>
我想在不使用 scriptlet 标签的情况下,在 jsp 中迭代并显示 hashmap 中的每个值和键。请帮我解决这个问题。
即使我尝试使用 scriplet 标记.. 但我只在迭代时获得哈希图中的最后一个值..
<%
ShoppingCart ob=new ShoppingCart();
HashMap<Integer,Products>newproductMap=new HashMap<Integer,Products>();
newproductMap=ob.showProducts();
Set<Integer>set = newproductMap.keySet();
for(Integer ent:set){
String name=newproductMap.get(ent).getProductName().toString();%>
<%=name%>
<%-- <%String value = ent.getValue().toString();%>
<%=value%>
--%>
<%}%>
【问题讨论】:
标签: jsp hashmap jstl scriptlet