Servlet 教程 之 Servlet 表单数据 7
Servlet 表单数据
将复选框数据传递到 Servlet 程序
当需要选择一个以上的选项时,则使用复选框。
下面是一个 HTML 代码实例 checkbox.html,一个带有两个复选框的表单。
<!DOCTYPE html>
百度
淘宝
下面是 CheckBox.java Servlet 程序,处理 Web 浏览器给出的复选框输入。
package com.baidu.test;
import java.io.IOException;
import java.io.PrintWriter;
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 CheckBox
*/
@WebServlet("/CheckBox")
public class CheckBox extends HttpServlet {
private static final long serialVersionUID = 1L;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>菜鸟按教程标识:</b>: " + request.getParameter("baidu") + "\n" + " <li><b>Google 标识:</b>: " + request.getParameter("google") + "\n" + " <li><b>淘宝标识:</b>: " + request.getParameter("taobao") + "\n" + "</ul>\n" + "</body></html>");}
// 处理 POST 方法请求的方法
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);}
}
设置对应的 web.xml:
<?xml version="1.0" encoding="UTF-8"?>
CheckBox
com.baidu.test.CheckBox
CheckBox
/TomcatTest/CheckBox