我有ProductServlet.java
从数据库List<Map<String, Object>> paramsList
获取 - 充满了带有参数的产品对象。然后我执行以下操作:request.setAttribute("paramList", paramsList);
并获取prodView.jsp
中的列表进行解析:
<form method="POST" action="editProduct">
...
<c:forEach var="map" items="${paramList}" >
<tr>
<td>Attributes</td>
<td><input type="text" name="attr" value="<c:out value="${map['attrName']}"/>" /></td>
</tr>
<tr>
<td>Values of attributes</td>
<td><input type="text" name="vals" value="<c:out value="${map['value']}"/>" /></td>
</tr>
</c:forEach>
...
假设用户修改了paramList。所以我想在list<Map<String, Object>>
(EditProductServlet.java
)中修改@WebServlet(urlPatterns = { "/editProduct" })
(其元素)。但我不知道该怎么做。当我尝试这个时,我什么也得不到:
String t = (String) request.getParameter("attr");
谢谢你的帮助!
答案 0 :(得分:2)
您需要使用getParameterValues(),它返回一个具有相同名称的参数数组。由于您要创建多个具有相同名称的文本框,即attr和vals。应该使用HttpSerletRequest的getParameterValues()方法代替getParameterValue()。
以下是完整的样本
Servlet代码
public class MapServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("do Get");
Map<String, String> values = new HashMap<String, String>();
values.put("1", "One");
values.put("2", "Two");
values.put("3", "Three");
values.put("4", "Four");
request.setAttribute("paramList", values);
RequestDispatcher rd = request.getRequestDispatcher("youruipage.jsp");
rd.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("do Post");
String keys[] = request.getParameterValues("attr");
String values[] = request.getParameterValues("vals");
for (String str1 : values) {
System.out.println(" - " + str1);
}
for (String str2 : keys) {
System.out.println(" - " + str2);
}
}
}
JSP片段:
<form method="POST" action="editProduct">
<h2> test</h2>
<table>
<c:forEach var="map" items="${requestScope.paramList}" >
<tr>
<td>Attributes</td>
<td><input type="text" name="attr" value="${map.key}" /></td>
</tr>
<tr>
<td>Values of attributes</td>
<td><input type="text" name="vals" value="${map.value}" /></td>
</tr>
</c:forEach>
</table>
<input type="submit" value= "submit"/>
</form>