表单数据处理通过request.getParameter()获取指定字段内容,通过request.getParameterValues()方式获取前端多个值以数组形式存储。
表单代码如下:
<!DOCTYPE html>
<html>
<head>
<title>用户注册</title>
<meta name="keywords" content="keyword1,keyword2,keyword3">
<meta name="description" content="this is my page">
<meta name="content-type" content="text/html; charset=UTF-8">
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
</head>
<body>
<form name="user" id="f1" action="servlet/userRegedit" method="post">
<table>
<tr>
<td>user name:</td>
<td><input type="text" name="username" id="login"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" id="password"></td>
</tr>
<tr>
<td>
<input type="radio" name="sex" value="1">男
<input type="radio" name="sex" value="2">女
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="ah" value="1">运动
<input type="checkbox" name="ah" value="2">玩
</td>
</tr>
<tr>
<td>
<select name="zw">
<option value="java">java</option>
<option value="php">php</option>
<option value="python">python</option>
</select>
</td>
</tr>
<tr>
<td>
<textarea rows="20" cols="30" name="bz"></textarea>
</td>
</tr>
<tr>
<td colspan="2"><input type="submit"></td>
</tr>
</table>
</form>
</body>
</html>
servlet代码如下:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取用户输入表单
String name = request.getParameter("username");
String password = request.getParameter("password");
String sex = request.getParameter("sex");
String[] hobby = request.getParameterValues("ah");
String gw = request.getParameter("zw");
String memo = request.getParameter("bz");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet Form</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.println(name);
out.println(password);
out.println(sex);
for(String x:hobby){
out.println(x);
}
out.println(gw);
out.println(memo);
out.print(this.getClass());
out.println(", using the GET method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
可以将前台输入所有内容读入并进行处理。