当需要选择一个以上的选项时,则使用复选框。
下面是一个 HTML 代码实例 checkbox.html,一个带有两个复选框的表单。
实例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>runoops 自学教程</title>
</head>
<body>
<form action="FormCheckboxServlet" method="POST" target="_blank">
<input type="checkbox" name="runoops" checked="checked" /> 自学教程 <input
type="checkbox" name="google" /> Google <input type="checkbox"
name="taobao" checked="checked" /> 淘宝 <input type="submit"
value="选择站点" />
</form>
</body>
</html>
下面是 FormCheckboxServlet.java Servlet 程序,处理 Web 浏览器给出的复选框输入。
实例
package com.runoops.test;
import java.io.*;
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 FormCheckboxServlet
*/
@WebServlet("/FormCheckboxServlet")
public class FormCheckboxServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public FormCheckboxServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 设置响应内容类型
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String title = "读取复选框数据";
String docType = "<!DOCTYPE html> \n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<ul>\n" +
" <li><b>runoops 自学教程:</b> "
+ request.getParameter("runoops") + "\n" +
" <li><b>Google 标识:</b> "
+ request.getParameter("google") + "\n" +
" <li><b>淘宝标识:</b> "
+ request.getParameter("taobao") + "\n" +
"</ul>\n" +
"</body></html>");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
上面的Servlet 类已经用了@WebServlet 注解,web.xml中可以不用配置。
上面的实例将显示下面的结果: