浏览 17401 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2005-08-04
[size=18]Ajax测试用例:[/size][前提条件]
安装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向客户端输出中文,需要编码转换。 [多此一举] 你需要了解tomcat工程。熟悉xmlHttpRequest,java servlet,html等知识。 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |
发表时间:2005-08-04
今天心情很好,因为我的ajax测试成功,公司的项目也会大进步,于是写下了上面的文字,与大家分享。要知道这是我郁闷两天的结果。
|
|
返回顶楼 | |
发表时间:2005-08-05
把onkeyup="validate();"改为onmouseout="validate();" 最好,不然才打了一个字就触发事件了.
|
|
返回顶楼 | |
发表时间:2005-08-05
确实是新手入门所急需的,thank you very much.
|
|
返回顶楼 | |
发表时间:2005-08-09
把bush改小泉试试,我出乱码了。
|
|
返回顶楼 | |
发表时间:2005-09-23
这几天才开始看ajax相关的东西,楼主的例子相当不错,谢谢分享。
我想补充一点,如下: 当 url="/servlet?submitId=submit”; req.open("GET", url, true);; req.onreadystatechange = callback; req.send(null);; url里面带参数时,在servlet里面可以用 request.getParameter("submitId");;来取得参数。但是如果改成 paras="submitId=submit"; url="/servlet"; req.open("GET", url, true);; req.onreadystatechange = callback; req.send(paras);; 再使用 request.getParameter("submitId");;取得的却是null? 这时候要在rep.open之后加上 xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); ; 然后才能取到值。 这时我刚刚遇到的一个小问题,觉得可能也会有人碰到,所以就贴上来了,希望对大家有用。 |
|
返回顶楼 | |
发表时间:2005-09-29
引用 来取得参数。但是如果改成
java代码: paras="submitId=submit"; url="/servlet"; req.open("GET", url, true); req.onreadystatechange = callback; req.send(paras); 再使用 java代码: request.getParameter("submitId"); 既然你都声明用GET了.但是querystring没有跟上去.本来就不符合HTTP RFC |
|
返回顶楼 | |
发表时间:2005-10-21
js和servlet写的有些繁琐了,
|
|
返回顶楼 | |
发表时间:2005-10-22
cnsdl 写道 把bush改小泉试试,我出乱码了。
1、JSP中: <%@ page contentType="text/html;charset=gb2312"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>AJAX</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="AJAX"> <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);; var url = "servlet/ValidateServlet?id=" + 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.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");; 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\n" + 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">AJAX</div> <input type="text" size="20" id="userid" name="id" value="java" onmouseout="validate();;" ondblclick="this.value='爪哇'"> </body> </html> 2、JAVA中 public void doGet(HttpServletRequest request,HttpServletResponse response); throws ServletException,IOException { response.setContentType("text/xml; CHARSET=utf8");; response.setHeader("Cache-Control","no-cache");; String targetId = request.getParameter("id");; System.out.println(targetId);; StringBuffer strbuf = new StringBuffer();; strbuf.append("<?xml version='1.0' encoding='GBK'?>\n");; strbuf.append("<info>\n");; if((targetId != null); && users.containsKey(targetId);); { targetId = java.net.URLDecoder.decode(targetId);; strbuf.append("<message>欢迎Welcome你!</message><name>" + targetId + "(^_^);</name>");; } else { strbuf.append("<message>错误Error:</message><name>" + targetId + "</name>");; System.out.println("invalid");; } strbuf.append("</info>\n");; response.getWriter();.write(strbuf.toString(););; } public void init(); throws ServletException { users.put("java","account data");; users.put("duke","account data");; users.put("coffee","account data");; users.put("j2se","account data");; users.put("j2ee","account data");; users.put("j2me","account data");; users.put("爪哇","account data");; users.put("咖啡","account data");; } |
|
返回顶楼 | |