Java进行时
      把握现在,成就未来!
posts - 23,comments - 30,trackbacks - 0
今天无意间看见一个这样的AJAX例子,觉得很有价值,于是便记录了下来,以供以后参考。
原文地址:http://hi.baidu.com/casa2/blog/item/7a6bc1c684e81c1f9d163df5.html
本例将在页面的参数以Get和POST两种方式传递到服务器,并回显到页面;

本例共包括两个主要文件getAndPostExample.html和GetAndPostExample.java以及一个配置文件web.xml
建立文件的步骤:
1.在Eclipse新建一个web project-->ajax1
2.在ajax1里面新建一个getAndPostExample.html
3.在ajax1里面新建一个servlet-->GetAndPostExample.java

getAndPostExample.html如下

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <title>getAndPostExamplel.html</title>
   
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
   
    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
    <script type="text/javascript">
        var xmlHttp;
        //创建XMLhttpRequest对象
        function createXMLHttpRequest() {
            if (window.ActiveXObject) {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            else if (window.XMLHttpRequest) {
                xmlHttp = new XMLHttpRequest();
            }
        }

        //生成传递到服务器的参数查询串,参数值由页面表单填写得到
       function createQueryString() {
            var firstName = document.getElementById("firstName").value;
            var middleName = document.getElementById("middleName").value;
            var birthday = document.getElementById("birthday").value;
            var queryString = "firstName=" + firstName + "&middleName=" + middleName
            + "&birthday=" + birthday;
            return queryString;
        }

        //点击按钮响应的Get方法主函数
        //Get方法把参数值以名=值方式在xmlHttp.open("GET", queryString, true)中传递,queryString的形式为URL?参数名=值&参数名=值...;而xmlHttp.send(null);

        function doRequestUsingGET() {
            createXMLHttpRequest();//第一步:创建XMLHttpRequest对象
            var queryString = "GetAndPostExample?";
            queryString = queryString + createQueryString()
            + "&timeStamp=" + new Date().getTime();//第二步:定义传递的参数值字符串
            xmlHttp.open("GET", queryString, true);//第三步:建立与服务器的请求
            xmlHttp.onreadystatechange = handleStateChange;//第四步:监听状态-->转到监听状态函数   
            xmlHttp.send(null);//第五步:发送请求,并且立即返回
        }

        //点击按钮响应的POST方法主函数
        //POST方法把参数值以名=值方式在xmlHttp.send(queryString)中传递,queryString的形式为参数名=值&参数名=值...;

        function doRequestUsingPOST() {
            createXMLHttpRequest();//第一步:创建XMLHttpRequest对象
            var url = "GetAndPostExample?timeStamp=" + new Date().getTime();
            var queryString = createQueryString();//第二步:定义传递的参数值字符串
            xmlHttp.open("POST", url, true);//第三步:建立与服务器的请求
            xmlHttp.onreadystatechange = handleStateChange;//第四步:监听状态-->转到监听状态函数
            xmlHttp.setRequestHeader("Content-Type",
            "application/x-www-form-urlencoded;");
            xmlHttp.send(queryString);//第五步:发送请求,并且立即返回
        }

        //监听状态函数
        function handleStateChange() {
            if(xmlHttp.readyState == 4) {
                if(xmlHttp.status == 200) {
                parseResults();//-->转到函数parseResults输出从服务器返的值
                }
            }
        }

        //在页面显示从服务器传来的结果
       function parseResults() {
            var responseDiv = document.getElementById("serverResponse");
            if(responseDiv.hasChildNodes()) {
            responseDiv.removeChild(responseDiv.childNodes[0]);
        }
        var responseText = document.createTextNode(xmlHttp.responseText);//
        responseDiv.appendChild(responseText);
        }
</script>
</head>

<body>
    <h1>Enter your first name, middle name, and birthday:</h1>
    <table>
        <tbody>
            <tr>
                <td>First name:</td>
                <td><input type="text" id="firstName"/>
            </tr>
            <tr>
                <td>Middle name:</td>
                <td><input type="text" id="middleName"/>
            </tr>
            <tr>
                <td>Birthday:</td>
                <td><input type="text" id="birthday"/>
            </tr>
        </tbody>
    </table>
    <form action="#">
        <input type="button" value="Send parameters using GET"
        onclick="doRequestUsingGET();"/>
<!--调用Get方法主函数-->
        <br/><br/>
        <input type="button" value="Send parameters using POST"
        onclick="doRequestUsingPOST();"/>
<!--调用POST方法主函数-->
    </form>
    <br/>
    <h2>Server Response:</h2>
    <div id="serverResponse"></div>
</body>
</html>

GetAndPostExample.java 如下

package com.ajax1;

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;

public class GetAndPostExample extends HttpServlet {

    protected void processRequest(HttpServletRequest request,
            HttpServletResponse response, String method)
            throws ServletException, IOException {
                //把响应内容类型设置为 text/xml
                response.setContentType("text/xml");
                //得到用户参数值
                String firstName = request.getParameter("firstName");
                String middleName = request.getParameter("middleName");
                String birthday = request.getParameter("birthday");
               //生成包含用户参数值的返回字符串
                String responseText = "Hello " + firstName + " " + middleName
                + ". Your birthday is " + birthday + "."
                + " [Method: " + method + "]";
                //写回浏览器
                PrintWriter out = response.getWriter();
                out.println(responseText);
                out.close();
            }
            protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
                //Get主函数调用processRequest,完成Get方法的参数接受,返回的过程
                processRequest(request, response, "GET");
            }
            protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
                //POST主函数调用processRequest,完成POST方法的参数接受,返回的过程
                processRequest(request, response, "POST");
            }
}

web.xml 如下

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
    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">
<servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>GetAndPostExample</servlet-name>
    <servlet-class>com.ajax1.GetAndPostExample</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>GetAndPostExample</servlet-name>
    <url-pattern>/GetAndPostExample</url-pattern>
</servlet-mapping>
<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

在这个简单的AJAX的例子里getAndPostExaple.html负责表单参数的输入和传递,而servlet GetAndPostExample.java负责在服务器端接受参数。参数传递时加的时间戳是保证URL的唯一性。
posted on 2008-04-21 12:22 biiau 阅读(5828) 评论(8)  编辑  收藏

FeedBack:
# re: 一个MyEclipse里的AJAX例子
2008-04-27 19:34 | ioworks
多谢!

这个真的是很好,一拷过去就可以运行!  回复  更多评论
  
# re: 一个MyEclipse里的AJAX例子
2008-09-27 14:42 | luanma
可是,返回的是乱码…………  回复  更多评论
  
# re: 一个MyEclipse里的AJAX例子[未登录]
2011-11-18 13:24 | 李鹏飞
@luanma
如果乱码给get 或者 post 方法 加上charset=“utf-8”;  回复  更多评论
  
# re: 一个MyEclipse里的AJAX例子
2012-02-23 19:40 | 编程小强
很感谢楼主分享  回复  更多评论
  
# re: 一个MyEclipse里的AJAX例子
2012-05-07 11:25 | 垂涎三尺
查询出  回复  更多评论
  
# re: 一个MyEclipse里的AJAX例子[未登录]
2013-08-16 23:07 | Ariel
为什么我试了之后Server Response下面没有响应出来呢?求助~  回复  更多评论
  
# re: 一个MyEclipse里的AJAX例子[未登录]
2013-08-17 12:00 | Ariel
知道怎么错了,是web.xml错了@Ariel
  回复  更多评论
  
# re: 一个MyEclipse里的AJAX例子
2013-11-07 09:48 | xlqcode
很不错 考过来就能运行  回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航: