以GET 和POST两种方式提交数据,这里以tomcat为服务器
html文件:testhtml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>动态查询显示结果
</title>
<script type="text/javascript">
var xmlHttp;
function createXMLHTTPRequest()
{
if(window.ActiveXObject)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest)
{
xmlHttp=new XMLHttpRequest();
}
}
function startRequest_GET()
{
createXMLHTTPRequest();
var url="PostData?"+sqlfactory()+"&timeStamp="+new Date().getTime();
xmlHttp.onreadystatechange=handleStateChange;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function startRequest_POST()
{
createXMLHTTPRequest();
var url="PostData?timeStamp="+(new Date()).getTime();
var sql=sqlfactory();
xmlHttp.open("POST",url,true);
xmlHttp.onreadystatechange=handleStateChange;
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
xmlHttp.send(sql);
}
function handleStateChange()
{
if(xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
document.getElementById("selectdata").innerHTML=xmlHttp.responseText;
}
}
}
function sqlfactory()
{
return "firstName="+document.getElementById("firstName").value+"&middleName="+document.getElementById("middleName").value+"&birthday="+document.getElementById("birthday").value;
}
</script>
</head>
<body>
<table>
<tr>
<td>姓:</td>
<td><input type="text" name="firstName"></td>
</tr>
<tr>
<td>名:</td>
<td><input type="text" name="middleName"></td>
</tr>
<tr>
<td>生日:</td>
<td><input type="text" name="birthday"></td>
</tr>
</table>
<form action="#">
<input type="button" value="GetData" onclick="startRequest_GET();"/><br><br>
<input type="button" value="PostData" onclick="startRequest_POST();"/><br><br>
<div id="selectdata"></div>
</form>
</body>
</html>
java文件:PostData.java
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class PostData extends HttpServlet
{
private void Go(HttpServletRequest req,HttpServletResponse res,String method)throws ServletException,IOException
{
res.setContentType("text/xml");
req.setCharacterEncoding("gb2312");
res.setCharacterEncoding("gb2312");
String firstName=req.getParameter("firstName");
String middleName=req.getParameter("middleName");
String birthday=req.getParameter("birthday");
String responseText="你的名字 <font color='red'>"+firstName+ " " +middleName +"</font>.你的生日:<font color='blue'>" + birthday + "</font>.[Method:" + method + "]";
res.getWriter().print(responseText);
}
protected void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
{
Go(req,res,"GET");
}
protected void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
{
Go(req,res,"POST");
}
}