1,在web包下新建html文件
书写所需要的表单,我的是一个简单的注册表
源码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#table1 {
margin: 0 auto;
}
</style>
</head>
<body>
//action的参数要与你创建的java类名一致
<form action="RegisterControlling" method="post">
<table border="1" cellspacing="0" id="table1" height="400" width="400">
<tr>
<td colspan="2" align="center">注册信息</td>
</tr>
<tr>
<td>用户名:</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td>性别</td>
<td>
<input type="radio" value="男" name="gender"> 男
<input type="radio" value="女" name="gender"> 女
</td>
</tr>
<tr>
<td>爱好</td>
<td>
<input type="checkbox" value="唱" name="hobby"> 乒乓球
<input type="checkbox" value="跳" name="hobby"> 足球
<input type="checkbox" value="篮球" name="hobby"> 篮球
</td>
</tr>
<tr>
<td>住址</td>
<td>
<select name="address">
<option value="成都">成都</option>
<option value="乐山">乐山</option>
<option value="自贡">自贡</option>
</select>
</td>
</tr>
<tr>
<td>备注:</td>
<td><textarea rows="5" cols="23" name="introduce"></textarea></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="注册">
<input type="reset" value="重置">
</td>
</tr>
</table>
</form>
</body>
</html>
2,通过服务器去获取表单数据
创建java类去接收客户端表单的数据
源码
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
//通过注解的方式配置web.xml文件(里面的参数填虚拟目录名,不要忘记‘/’ 不然会出现404)
@WebServlet("/RegisterControlling")
public class RegisterControlling extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置对客户端请求进行重新编码为UTF-8,否则会出现乱码
req.setCharacterEncoding("UTF-8");
//指定对服务器响应进行重新编码为UFT-8,同时浏览器也是根据这个参数来就行重写编码(又称解码)
resp.setCharacterEncoding("UTF-8");
//使客户端浏览器,区分不同种类的数据,这里是html所有设置为text/html
//后面就是设置编码,所以写了setContentType()后上面的resp.setCharacterEncoding("UTF-8")可以不用写
resp.setContentType("text/html;charset=UTF-8");
//通过客户端表单所设置的name获取它的值
String username = req.getParameter("username");
String password = req.getParameter("password");
String gender = req.getParameter("gender");
//因为多选框可能会获得多个值,所以需要用数组去接收它,在用Arrays.toString()方法将它转换为字符串
String[] hobbies = req.getParameterValues("hobby");
String address = req.getParameter("address");
String introduce = req.getParameter("introduce");
//输出
System.out.println(username+","+password+","+gender+","+ Arrays.toString(hobbies)+","+address+","+introduce);
}
}
3,运行Tomcat执行代码 填写数据,然后点击注册
点击注册后将会响应到服务器页面
4,查看服务器数据
到这里Servlet将表单数据传送到后台的方法就结束了,希望对你有帮助!!!