最近剛開始學AJAX的知識,這裏介紹一個簡單的Myeclipse+AJAX+Servlet項目。css
此項目包含3個文件:index.jsp、check.java。還有一個須要配置的文件是:web.xml,此文件在/Webroot/WEB-INF目錄下,在創建工程的時候選中一個複選框就會有此文件。html
此項目的完成步驟:前端
1.創建index.jsp文件,輸入如下代碼:java
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 5 %> 6 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 8 <html> 9 <head> 10 <base href="<%=basePath%>"> 11 12 <title>My JSP 'index.jsp' starting page</title> 13 <meta http-equiv="pragma" content="no-cache"> 14 <meta http-equiv="cache-control" content="no-cache"> 15 <meta http-equiv="expires" content="0"> 16 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 17 <meta http-equiv="description" content="This is my page"> 18 19 <link rel="stylesheet" type="text/css" href="styles.css"> 20 21 <script> 22 var xmlHttpReq; 23 //建立一個XmlHttpRequest對象 24 function createXmlHttpRequest() 25 { 26 window.alert("進入到createXmlHttpRequest()函數"); 27 if(window.XMLHttpRequest) 28 { 29 xmlHttpReq = new XMLHttpRequest();//非IE瀏覽器 30 }else 31 { 32 xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");//IE瀏覽器 33 } 34 } 35 //檢測用戶名是否已經被註冊 36 function checkUser() 37 { 38 window.alert("進入到checkUser()函數"); 39 var username = document.getElementById("user").value; 40 if(username=="") 41 { 42 alert("用戶名必須填寫!"); 43 return false; 44 } 45 //首先建立對象 46 createXmlHttpRequest(); 47 //指明準備狀態改變時回調的函數名 48 xmlHttpReq.onreadystatechange=handle; 49 //嘗試以異步的get方式訪問某個URL 50 //請求服務器端的一個servlet 51 //var url = "/web06/Servlet/" 52 var url = "./servlet/Check?username="+username;//+Math.random(); 53 window.alert(username); 54 xmlHttpReq.open("get",url,true); 55 //向服務器發送請求 56 xmlHttpReq.send(); 57 window.alert("已經發送數據"); 58 } 59 //狀態發生改變時回調的函數 60 function handle() 61 { 62 //準備狀態爲4 63 window.alert("進入到handle()函數"); 64 if(xmlHttpReq.readyState==4) 65 { 66 window.alert("響應已完成;您能夠獲取並使用服務器的響應了。"); 67 //響應狀態碼爲200,表明一切正常 68 if(xmlHttpReq.status==200) 69 { 70 window.alert("交易成功 "); 71 var res = xmlHttpReq.responseText; 72 var result = document.getElementById("result"); 73 result.innerHTML = "<font color=red>"+res+"</font>"; 74 } 75 } 76 } 77 </script> 78 </head> 79 80 <body> 81 <center><h1>表單註冊</h1></center> 82 <hr> 83 姓名: 84 <input type="text" id="user"> 85 <input type="button" value="檢測用戶名" onclick="checkUser()"> 86 <span id="result"></span> 87 </body> 88 </body> 89 </html>
2.創建Check.java文件,此文件所屬的packet名稱爲com.wepull.servlet,代碼以下:web
1 package com.wepull.servlet; 2 3 import java.io.IOException; 4 import javax.servlet.ServletException; 5 import javax.servlet.http.HttpServlet; 6 import javax.servlet.http.HttpServletRequest; 7 import javax.servlet.http.HttpServletResponse; 8 //@WebServlet (name="Check",urlPatterns={"/diaocha.do"}) 9 public class Check extends HttpServlet { 10 11 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 12 //解決返回中文亂碼問題 13 //response.getWriter().println("str"); 14 response.setCharacterEncoding("utf-8"); 15 16 String user = request.getParameter("username"); 17 response.getWriter().println(user); 18 response.getWriter().println(request); 19 System.out.println(user+"傳過來是null"); 20 System.out.println(request); 21 System.out.println(user+"傳過來是null"); 22 //解決接收中文亂碼問題 23 //user = new String(user.getBytes("iso-8859-1"),"utf-8"); 24 if(user == "") 25 { 26 System.out.println("user is nullD!!!"); 27 } 28 else 29 { 30 System.out.println(user); 31 32 String msg = null; 33 if("jing".equals(user)) 34 { 35 msg = "用戶名已經被佔用!"; 36 }else 37 { 38 msg = "用戶名能夠使用!"; 39 } 40 response.getWriter().println(msg); 41 } 42 43 } 44 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 45 doGet(request,response); 46 } 47 }
3.修改web.xml文件瀏覽器
修改前:服務器
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>web08</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> </web-app>
修改後:app
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>web08</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>Check</servlet-name> <servlet-class>com.wepull.servlet.Check</servlet-class> </servlet> <servlet-mapping> <servlet-name>Check</servlet-name> <url-pattern>/servlet/Check</url-pattern> </servlet-mapping> </web-app>
其中web08是個人項目名稱。dom
重要提醒(由於這個錯誤我Debug了好幾天。。。)eclipse
var url = "./servlet/Check?username="+username;//+Math.random();
必定要注意""中的第一個字符 " ." ,不然Servlet就會收不到前端發送的數據(url不正確)。
4.最後運行出來結果以下:
4.1
4.2
ps:程序運行中和運行結果會有一些調試的代碼,請你們自行忽略。