最近小弟在学习ajax,就随便做了一个ajax请求servlet并返回结果的小测试,但是一直调不通,一直是“网页上有错误”,看了一下XMLHttpRequest的值,一直是0。这是怎么回事啊?那位高手请指点一下,不胜感激!!!!!
希望实现功能:通过URL请求把参数传给ajaxServlet类处理,并显示处理结果!
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <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="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <script type="text/javascript"> var xmlHttp; function createXMLHttpRequest() { try{ xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) { try{ xmlHttp = new XMLHttpRequest(); } catch(e) { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } } } function startRequest() { createXMLHttpRequest(); xmlHttp.onreadystatechange = handleXMLHttpRequest; xmlHttp.open("GET",basePath+"servlet/ajaxServlet?username=pangbo&password=19871201",true); send(null); } function handleXMLHttpRequest() { if(xmlHttp.readyState==4) { if(xmlHttp.state==200) { alert(xmlHttp.responseText()); } } } </script> </head> <body> <input name="submit" value="提交" type="submit" onclick="startRequest()"/> </body> </html>
ajaxServlet类:
package com.ac.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.*; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ajaxServlet extends HttpServlet{ /** * */ private static final long serialVersionUID = 1L; public void init(ServletConfig config) throws ServletException { super.init(config); } public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException { String username = request.getParameter("username"); String password = request.getParameter("password"); String responseText = username+"的密码是"+password+"请牢记!!!!"; PrintWriter out = response.getWriter() ; out.println(responseText); out.close(); } }
web.xml(应该没有配错)
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>ajaxServlet</servlet-name> <servlet-class>com.ac.servlet.ajaxServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>ajaxServlet</servlet-name> <url-pattern>/servlet/ajaxServlet</url-pattern> </servlet-mapping> </web-app>