html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>读取复选框数据</title>
</head>
<body>
<form action="demo03" method="post" target="_blank">
<label>数学:
<input type="checkbox" name="math" value="数学">
</label><br/>
<label>英语:
<input type="checkbox" name="English" value="英语">
</label><br/>
<label>化学:
<input type="checkbox" name="chemistry" value="化学">
</label><br/>
<label>历史:
<input type="checkbox" name="history" value="历史">
</label><br/>
<label>物理:
<input type="checkbox" name="physics" value="物理">
</label><br/>
<label>语文:
<input type="checkbox" name="chinese" value="语文">
</label><br/>
<input type="submit">
</form>
</body>
</html>
Servlet代码
public class ServletDemo03 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
PrintWriter writer = resp.getWriter();
String header="<!DOCTYPE html>\n" +
"<html lang=\"en\">\n" +
"<head>\n" +
" <meta charset=\"UTF-8\">\n" +
" <title>读取复选框数据</title>\n" +
" <style>\n" +
" table,tr,td,th{\n" +
" border: black 1px solid;\n" +
" }\n" +
" table{\n" +
" border-collapse: collapse;\n" +
" }\n" +
" </style>\n" +
"</head>\n" +
"<body>\n" +
" <table>\n" +
" <caption>科目</caption>\n" +
" <tr>\n" +
" <th>参数名称</th>\n" +
" <th>参数值</th>\n" +
" </tr>";
writer.println(header);
Map<String, String[]> parameterMap = req.getParameterMap();
for(Map.Entry<String,String[]> entry: parameterMap.entrySet()){
String name = entry.getKey();
String[] values = entry.getValue();
for(String value : values){
writer.println("<tr>\n" +
" <td>"+ name +"</td>\n" +
" <td>"+value+"</td>\n" +
" </tr>");
}
}
writer.println();
writer.println(" </table>\n" +
"</body>\n" +
"</html>");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
结果图
|