获取表单数据的两种方法:
1、使用getParameter()方法获取元素
2、使用Enumeration(枚举)
首先创建html界面:
<html>
<head>
<meta charset="UTF-8">
<title>get data</title>
</head>
<body>
<form method="get" action="相应的servlet">
用户名<input type="text" name="uname" /><br/>
密码<input type="password" name="pwd"/><br/>
性别 <input type="radio" name="sex" value="man"/>男
<input type="radio" name="sex" value="woman"/>女<br/>
爱好 <input type="checkbox" name="hobby" value="football"/>足球
<input type="checkbox" name="hobby" value="basketball"/>篮球 <input type="checkbox" name="hobby" value="volleyball"/>排球<br/>
<input type="submit" value="注册"/>
<input type="reset" value="重置"/>
</form>
</body>
</html>
方法一:使用getParameter()方法
public class GetDataServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置编码格式
req.setCharacterEncoding("utf-8"); resp.setContentType("text/html;charset=utf-8");
String uname = req.getParameter("uname");
String pwd = req.getParameter("pwd");
String sex = req.getParameter("sex");
String [] hobby = req.getParameterValues("hobby");
//响应处理结果
resp.getWriter().write(uname);
resp.getWriter().write("<br/>");
resp.getWriter().write(pwd);
resp.getWriter().write("<br/>");
resp.getWriter().write(sex);
resp.getWriter().write("<br/>");
for(int i=0;i<hobby.length;i++) {
resp.getWriter().write(hobby[i]+" ");
}
}
}
执行结果:
方法二:使用Enumeration(枚举)
public class GetDataServlet2 extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
//创建枚举
Enumeration<String> data = req.getParameterNames();
while(data.hasMoreElements()) {
String str = (String) data.nextElement();
String[] strs = req.getParameterValues(str);
for(String s : strs) {
resp.getWriter().write(s+"<br/>");
}
}
}
}
运行结果: