尝试使用netbeans从servlet.Am中检索从HTML提交的数据,并尝试获取getAttributes()返回的枚举。 html是
<html>
<body>
<center>
<form name="Form1" action="http://localhost:8080/DemoWeb/TwoParServlet">
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br>
<br>
<B>Country:</B>
<select name="country" size="1">
<option value="India">India</option>
<option value="Srilanka">Srilanka</option>
<option value="Chinae">China</option>
</select>
<br>
<br>
<input type=submit value="Submit">
</form>
</center>
</body>
</html>
servlet是
public class TwoParServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String color = request.getParameter("color");
String country = request.getParameter("country");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<p>The selected color is: ");
pw.println(color);
pw.println("<p>The selected country is: ");
pw.println(country);
Enumeration names;
names = request.getAttributeNames();
pw.println("<p> First value received = " + names.nextElement());
//pw.println("<p> First value received = " + names.nextElement());
pw.close();
}
}
当我运行项目时出现此错误
异常报告消息说明服务器遇到内部错误,导致无法完成此请求。
例外
java.util.NoSuchElementException
java.util.HashMap$HashIterator.nextEntry(HashMap.java:929)
java.util.HashMap$KeyIterator.next(HashMap.java:960)
java.util.Collections$2.nextElement(Collections.java:3665)
p1.TwoParServlet.doGet(TwoParServlet.java:36)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
可能出了什么问题?
答案 0 :(得分:1)
您应该使用getParameterNames()
代替getAttributeNames
。
Enumeration parameterNames = request.getParameterNames();
有关了解属性和参数之间差异的详细信息,请参阅this question。
答案 1 :(得分:1)
您只需检查names
的大小,它就会为零。
所以这意味着request.getAttributeNames()
没有返回任何内容。
使用request.getParameterNames()
代替request.getAttributeNames()
。