java网络编程-Ajax+servlet实例
时间:2007-10-17 来源:xiang588
Ajax异步请求,servlet产生随机数据,Html页面无刷新显示。
运行环境:jdk1.5+tomcat 5.5
一、ajaxServlet.java
package com;import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Random;
public class ajaxServlet extends HttpServlet{
private static final String CONTENT_TYPE="text/xml; charset=gb2312";
public void init() throws ServletException{}
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
response.setContentType(CONTENT_TYPE);
response.setHeader("Cache-Control","no-cache");
response.setHeader("Pragma","no-cache");
response.setDateHeader("Expires",0);
PrintWriter out=response.getWriter();
String action=request.getParameter("action");
if(("send").equals(action)){
Random random = new Random();
String AA=Integer.toString(Math.abs(random.nextInt()));
String BB=Integer.toString(Math.abs(random.nextInt()));
String CC=Integer.toString(Math.abs(random.nextInt()));
String DD=Integer.toString(Math.abs(random.nextInt()));
StringBuffer sb=new StringBuffer();
sb.append(AA); sb.append("@@@");
sb.append(BB); sb.append("@@@");
sb.append(CC); sb.append("@@@");
sb.append(DD);
out.write(sb.toString());
out.close();
} }}
二、testajax.html
<html>
<head>
<title>AJAX.html</title>
</head>
<body onload="MyShow()">
<table width="47%" height="23" border="0" cellpadding="1" cellspacing="0" id="tb">
<tr><td>代码</td>
<td>价格</td>
</tr>
</table>
<form>
<p>输入股票代码:
<input type="text" size="14" name="phone" id="phone"/>
</p>
<p>你交易的数量:</p>
<p><textarea name="order" rows="6" cols="50" id="order"></textarea></p>
<p><input type="submit" value="提交" id="submit" /></p>
</form>
</body>
三、web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<display-name>Welcome to Tomcat</display-name>
<description>
Welcome to Tomcat
</description>
<servlet>
<servlet-name>AajaxServlet</servlet-name>
<servlet-class>com.ajaxServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AajaxServlet</servlet-name>
<url-pattern>/AajaxServlet</url-pattern>
</servlet-mapping>
</web-app>