form表单提交到servlet怎么获取值
Servlet的5种方式实现表单提交(注册小功能),后台获取表单数据
用servlet实现一个注册的小功能 ,后台获取数据。
注册页面:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="/RequestDemo/RequestDemo3" method="post">
用户名:<input type="text" name="userName"><br/>
密码:<input type="text" name="pwd"><br/>
性别:<input type="radio" name="sex" value="男" checked="checked">男
<input type="radio" name="sex" value="女">女<br/>
爱好:<input type="checkbox" name="hobby" value="足球">足球
<input type="checkbox" name="hobby" value="篮球">篮球
<input type="checkbox" name="hobby" value="排球">排球
<input type="checkbox" name="hobby" value="羽毛球">羽毛球<br/>
所在城市:<select name="city">
<option>---请选择---</option>
<option value="bj">北京</option>
<option value="sh">上海</option>
<option value="sy">沈阳</option>
</select>
<br/>
<input type="submit" value="点击注册">
</form>
</body>
</html>
人员实体类: 注意:人员实体类要与表单中的name一致,约定要优于编码
package com.chensi.bean;
//实体类中的字段要与表单中的字段一致,约定优于编码
public class User {
private String userName;
private String pwd;
private String sex;
private String[] hobby;
private String city;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String[] getHobby() {
return hobby;
}
public void setHobby(String[] hobby) {
this.hobby = hobby;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
接收方法一: Servlet页面(后台接收数据方法一)
package com.chensi;
import java.io.IOException;
import java.util.Iterator;
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 获得填写的表单数据
*/
@WebServlet("/RequestDemo3")
public class RequestDemo3 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
//获取传过来的表单数据,根据表单中的name获取所填写的值
String userName = request.getParameter("userName");
String pwd = request.getParameter("pwd");
String sex = request.getParameter("sex");
String[] hobbys = request.getParameterValues("hobby");
System.out.println(userName);
System.out.println(pwd);
System.out.println(sex);
for (int i = 0; hobbys!=null&&i < hobbys.length; i++) {
System.out.println(hobbys[i]+"\t");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}