本篇博客将在上一篇博客《Servlet第一个示例》的基础上继续介绍,Servlet如何处理客户端的请求,获得客户端的请求消息。
首先我们新建一个静态页面index.html,用于向Servlet提交请求。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Servlet</title>
</head>
<body>
<form action="Test" method="POST">
<table>
<tr>
<td>用户编号</td>
<td><input type="text" name="userId"></td>
</tr>
<tr>
<td>用户名称</td>
<td><input type="text" name="userName"></td>
</tr>
<tr>
<td>用户性别</td>
<td><select name="userSex"><option value="1">男</option>
<option value="2">女</option></select></td>
</tr>
<tr>
<td>兴趣爱好</td>
<td><input type="checkbox" name="interest1">兴趣1 <input
type="checkbox" name="interest2">兴趣2</td>
</tr>
<tr>
<td colspan="2"><input type="submit"></td>
</tr>
</table>
</form>
</body>
</html>
然后,我们需要修改Test中的方法,因为页面采用POST方式提交,所以在Test Servlet中,我们仅对Post的请求做处理。
package com.gujin.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Test extends HttpServlet
{
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
request.setCharacterEncoding("UTF-8");
// 获得请求头信息
System.out.println("======HEAD INFO======");
Enumeration enumeration = request.getHeaderNames();
while (enumeration.hasMoreElements())
{
String name = (String) enumeration.nextElement();
Enumeration headers = request.getHeaders(name);
while (headers.hasMoreElements())
{
System.out.println(name + ":" + headers.nextElement());
}
}
// 获得请求参数
System.out.println("======REQUEST PARAM======");
// 获得指定参数
// request.getParameter("userId");
// 获得所有请求参数名称
// request.getParameterNames();
// 获得请求参数集合
// request.getParameterMap();
Enumeration names = request.getParameterNames();
while (names.hasMoreElements())
{
String name = (String) names.nextElement();
System.out.println(name + ":" + request.getParameter(name));
}
PrintWriter writer = response.getWriter();
writer.print("Hello Servlet");
writer.flush();
writer.close();
}
}
启动服务器后访问:http://localhost/Servlet/
输入一些内容后提交,我们会看到服务端的后台会输出如下内容(内容可能会不一样):
======HEAD INFO======
accept:image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, a
pplication/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, /
referer:http://localhost/Servlet/
accept-language:zh-CN
user-agent:Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 3.0.04506.30; .NET CLR 2.0
.50727; hwvcloud4; hwcloud4)
content-type:application/x-www-form-urlencoded
accept-encoding:gzip, deflate
host:localhost
content-length:77
connection:Keep-Alive
cache-control:no-cache
======REQUEST PARAM======
userId:jianggujin
userSex:1
interest2:on
userName:蒋固金
这样我么就可以根据客户端请求的内容做相应的业务处理。