这几天把ajax前面的基础大概了解了下,基本知道了ajax的原理。
下午继续在看书,做了个日期数据验证的小例子。
页面validation.html代码
<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" >
<% ... @ page contentType="text/html;charset=GBK" %>
< html >
< head >
< title > validation.html </ title >
< script type ="text/javascript" > ...
var xmlHttp;
function createXMLHttpRequest()...{
if(window.ActiveXObject)...{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}else...{
xmlHttp = new XMLHttpRequest;
}
}
function validate()...{
createXMLHttpRequest();
var date = document.getElementById("birthDay");
var url = "/ajaxTest/ValidationServlet?birthDate=" + escape(date.value);
xmlHttp.open("GET",url,true);
xmlHttp.onreadystatechange = callback;
xmlHttp.send(null);
}
function callback()...{
if(xmlHttp.readystate == 4)...{
if(xmlHttp.status == 200)...{
var mes = xmlHttp.responseXML.getElementsByTagName("message")[0].firstChild.nodeValue;
var val = xmlHttp.responseXML.getElementsByTagName("passed")[0].firstChild.nodeValue;
setMessage(mes,val);
}
}
}
function setMessage(message,isValid)...{
var messageArea = document.getElementById("dateMessage");
var fontColor = "red";
if(isValid == "true")...{
fontColor = "green";
}
messageArea.innerHTML = "<font color = " + fontColor + ">" + message + "</font>";
}
</ script >
</ head >
< body >
< h1 > Ajax Validation Example </ h1 >
Birthday: < input type ="text" id ="birthDay" onChange ="validate();" >< div id ="dateMessage" ></ div >
</ body >
</ html >
servlet 代码ValidationServlet.java
package
org.jason.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ValidationServlet extends HttpServlet ... {
/** *//**
* Constructor of the object.
*/
public ValidationServlet() ...{
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;charset=GBK");
PrintWriter out = response.getWriter();
boolean passed = validateDate(request.getParameter("birthDate"));
response.setHeader("Cache-Control","no-cache");
String message = "日期格式错误 请按(YYYY/MM/DD)输入";
if(passed)...{
message = "输入格式正确";
}
out.println("<?xml version='1.0' encoding='GBK'?>");
out.println("<response>");
out.println("<passed>" + Boolean.toString(passed) + "</passed>");
out.println("<message>" + message + "</message>");
out.println("</response>");
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 ...{
doGet(request,response);
}
/** *//**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occure
*/
public void init() throws ServletException ...{
// Put your code here
}
protected boolean validateDate(String date)...{
boolean isValid = true;
if(date!=null)...{
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
try ...{
formatter.parse(date);
} catch (ParseException e) ...{
// TODO Auto-generated catch block
e.printStackTrace();
isValid = false;
}
}else...{
isValid = false;
}
return isValid;
}
}
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ValidationServlet extends HttpServlet ... {
/** *//**
* Constructor of the object.
*/
public ValidationServlet() ...{
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;charset=GBK");
PrintWriter out = response.getWriter();
boolean passed = validateDate(request.getParameter("birthDate"));
response.setHeader("Cache-Control","no-cache");
String message = "日期格式错误 请按(YYYY/MM/DD)输入";
if(passed)...{
message = "输入格式正确";
}
out.println("<?xml version='1.0' encoding='GBK'?>");
out.println("<response>");
out.println("<passed>" + Boolean.toString(passed) + "</passed>");
out.println("<message>" + message + "</message>");
out.println("</response>");
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 ...{
doGet(request,response);
}
/** *//**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occure
*/
public void init() throws ServletException ...{
// Put your code here
}
protected boolean validateDate(String date)...{
boolean isValid = true;
if(date!=null)...{
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
try ...{
formatter.parse(date);
} catch (ParseException e) ...{
// TODO Auto-generated catch block
e.printStackTrace();
isValid = false;
}
}else...{
isValid = false;
}
return isValid;
}
}
在这里面遇到一个问题,那就是返回来的 responseText 或 responseXML 的值中含有中文就变乱码。
一开始只设置了response.setContentType("text/xml");
即使在下面设置out.println("<?xml version='1.0' encoding='GBK'?>"); 也不能解决中文乱码问题。
最后在网上找到一定要设置成response.setContentType("text/xml;charset=GBK");才能解决。。
看着问号变中文,就是那回事