Ajax入門執行個體

來源:互聯網
上載者:User
安裝jdk1.4和tomcat5.0.28,IE5.5獲FireFox。進入正題

[1]寫index.jsp檔案

<%@ page contentType="text/html;charset=gb2312"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

  <head>

    <title>My JSP 'index.jsp' starting page</title>

    <meta http-equiv="pragma" content="no-cache">

    <meta http-equiv="cache-control" content="no-cache">

    <meta http-equiv="expires" content="0">

    <meta http-equiv="description" content="This is my page">

    <link rel="stylesheet" type="text/css" href="styles.css">

  </head>

 

  <body>

    <script type="text/javascript">

    var req;

     function validate() {

         var idField = document.getElementById("userid");

         var url = "servlet/ValidateServlet?id=" + escape(idField.value);

         if (window.XMLHttpRequest) {

             alert("0");

             req = new XMLHttpRequest();

         }else if (window.ActiveXObject) {

             alert("1");

             req = new ActiveXObject("Microsoft.XMLHTTP");

         }

        if(req){

            req.open("GET", url, true);

             req.onreadystatechange = callback;

            req.send(null);       

         }

    }

function callback() {

    if (req.readyState == 4) {

        if (req.status == 200) {

                 parseMessage();

                
// update the HTML DOM based on whether or not message is valid

        }else{

            alert ("Not able to retrieve description" + req.statusText);

        }      

    }

}

function parseMessage() {

    var message = req.responseXML.getElementsByTagName("message")[0];

    var name = req.responseXML.getElementsByTagName("name")[0];

    setMessage(message.firstChild.data,name.firstChild.data);

}

 function setMessage(message,name) {

     var userMessageElement = document.getElementById("userIdMessage");

     userMessageElement.innerHTML = "<font color=\"red\">" + message + " you "+name+"</font>";

 }

</script>

<div id="userIdMessage"></div>

    <input type="text"

            size="20"

              id="userid"

            name="id"

         onkeyup="validate();">

  </body>

</html>

[2] 寫servlet/ValidateServlet.java類

/*

 * 建立日期 2005-8-3

 *

 * TODO 要更改此產生的檔案的模板,請轉至

 * 視窗 - 喜好設定 - Java - 代碼樣式 - 代碼模板

 */

package com;//com包需要自己建立.

 

import java.io.IOException;

import java.io.PrintWriter;

import java.util.HashMap;

 

import javax.servlet.ServletConfig;

import javax.servlet.ServletContext;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

/**

 * @author Administrator

 *

 * TODO 要更改此產生的類型注釋的模板,請轉至

 * 視窗 - 喜好設定 - Java - 代碼樣式 - 代碼模板

 */

public class ValidateServlet extends HttpServlet {

 

    /**

     * Constructor of the object.

     */

  

    private ServletContext context;

    private HashMap users = new HashMap();

 

    public ValidateServlet() {

        super();

    }

 

    /**

     * Destruction of the servlet. <br>

     */

    public void destroy() {

        super.destroy(); // Just puts "destroy" string in log

        // Put your code here

    }

 

    /**

     * The doGet method of the servlet. <br>

     *

     * This method is called when a form has its tag value method equals to get.

     *

     * @param request the request send by the client to the server

     * @param response the response send by the server to the client

     * @throws ServletException if an error occurred

     * @throws IOException if an error occurred

     */

    public void doGet(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        response.setContentType("text/xml");

        response.setHeader("Cache-Control", "no-cache");

      

        String targetId = request.getParameter("id");

        System.out.println(targetId.trim());

 

        if ((targetId != null) && users.containsKey(targetId.trim())) {

 

                         
response.getWriter().write("<info><message>welcome</message><name>sdl</name></info>");

        } else {

 

                 
response.getWriter().write("<info><message>kill</message><name>bush</name></info>");

                System.out.print("invalid");

            }

 

 

    }

    /**

     * Initialization of the servlet. <br>

     *

     * @throws ServletException if an error occure

     */

    public void init(ServletConfig config) throws ServletException {

        this.context = config.getServletContext();

        users.put("greg","account data");

        users.put("duke","account data");

 

    }

 

}

[3]寫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>ValidateServlet</servlet-name>

    <servlet-class>com.ValidateServlet</servlet-class>

  </servlet>

 

  <servlet-mapping>

    <servlet-name>ValidateServlet</servlet-name>

    <url-pattern>/servlet/ValidateServlet</url-pattern>

  </servlet-mapping>

</web-app>

[4]說明:
你可以在IE或FireFox裡測試,在文本輸入框裡輸入,當按鍵抬起,會在層中顯示”kill you bush”。其中index.htm中的styles.css只是美化頁面,沒有列出來原始碼。如果在servlet向用戶端輸出中文,需要編碼轉換。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.