入门:HTML表单与Java 后台交互(复选框提交)

时间:2023-03-08 17:35:53

仅仅给出部分关键代码:

HTML form code:

<form action="JavaFormTest" method="post" name="Form">
<p>
清输入用户名:<input type="text" name="username"/><br />
请输入用户密码:<input type="password" name="password" /><br />
</p>
请选择你的课程<br />
<p>
<input type="checkbox" name="checkbox" value="足球" />足球
<input type="checkbox" name="checkbox" value="篮球" /> 篮球
<input type="checkbox" name="checkbox" value="乒乓球" />乒乓球
<input type="checkbox" name="checkbox" value="排球" />排球球
</p>
<input type="button" name="but" onclick="submit()" value="提交" />
</form>

JavaFormTest.java 处理程序doPost 部分:

protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
String username = request.getParameter("username");
String password = request.getParameter("password");
String[] list = request.getParameterValues("checkbox");
if (username.isEmpty())
out.println("name is empty!<br />");
else
out.println("name:" + username + "<br />"); if (password.isEmpty())
out.println("password is empty!<br />");
else
out.println("password:" + password + "<br />"); if (list == null)
out.println("none list");
else {
out.println("list: <br />");
for (int i=0;i<list.length;i++) {
out.println("第 "+(i+1)+" 课程是:"+ list[i]+"<br />");
}
}
}