1. 程式人生 > >Servlet+AJAX實現資料處理顯示

Servlet+AJAX實現資料處理顯示

實現功能:在輸入框中輸入字元,用AJAX傳到後臺Servlet處理後加上隨機數,並返回到前臺顯示。
一、寫前臺jsp頁面index.jsp

	  <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'index.jsp' starting page</title>
    
	<script type="text/javascript">
	/*
		ajax 的幾個步驟:
		1、建立XmlHttpRequest物件
		2、設定回撥函式
		3、使用Open方法建立與伺服器的連線
		4、向伺服器傳送資料
		5、在回撥函式中針對不同響應狀態進行處理
	*/
		var xmlHttp;
		function createXMLHttpRequest(){   //1建立XmlHttpRequest物件
			if(window.ActiveXObject){
				try{
					xmlHttp = new ActiveXObject("Microsoft.XMLHttp");
				}catch(e){
					alert("Error!!!");
				}
			}else{
				xmlHttp = new XMLHttpRequest();
			}
		}

		function showMes(){		//2設定回撥函式
			if(xmlHttp.readyState==4){  //資料接收完成並可以使用
				if(xmlHttp.status==200){ //http狀態OK
				//5、在回撥函式中針對不同響應狀態進行處理
					document.getElementById("sp").innerHTML = xmlHttp.responseText; //伺服器的響應內容
				}else{
					alert("出錯:"+xmlHttp.statusText);  //HTTP狀態碼對應的文字
				}
			}
		}
		/**
		//這是GET方法傳送
		function getMes(){
			createXMLHttpRequest();
			var txt = document.getElementById("txt").value;
			var url="servlet/AjaxServlet?txt="+txt;
			url = encodeURI(url);  //轉換碼後再傳輸
			xmlHttp.open("GET",url,true);  //3使用Open方法建立與伺服器的連線
			xmlHttp.onreadystatechange=showMes; 
			xmlHttp.send(null); //4向伺服器傳送資料
		}
		*/
		/**
		*這是post方法
		*/
		function postMes(){
			createXMLHttpRequest();
			var txt = document.getElementById("txt").value;
			var url = "servlet/AjaxServlet";
			var params = "username="+txt;
		//	alert(params);
			xmlHttp.open("POST",url,true);
			xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
			xmlHttp.send(params);
			xmlHttp.onreadystatechange = showMes;
			
		}
	</script>
  </head>
  <body>
   <input type="text" id="txt"/>
   <input type="button" value="query" onclick="postMes()" />
   <span id="sp"></span>
  </body>
</html>


二、寫後臺Servlet加random隨機數,關鍵程式碼如下:

public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.setCharacterEncoding("utf-8"); //用utf-8轉換獲得傳輸過來的碼
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		String txt = request.getParameter("txt");
		
//		String tx = new String(txt.getBytes("iso-8859"),"utf-8");
		out.print("txt="+txt+Math.random());
		out.flush();
		out.close();
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @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 doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		String username = request.getParameter("username");
//		String txt = new String(username.getBytes("ISO-8859-1"),"UTF-8");
		String txt = new String(username);
		out.print("txt="+txt+":"+Math.random());
		
		out.flush();
		out.close();
	}