頁面:Validation.Html
<%@ page contentType="text/Html; charset=GBK" %>
<Html>
<head>
<title>
使用AJax進行驗證
</title>
<script type="text/Javascript">
//XMLHttpRequest對象
var XMLHttp;
//創建XMLHttpRequest對象
function createXMLHttpRequest(){
if (window.ActiveXObject){
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}
}
//驗證方法
function validate(){
//創建對象
createXMLHttpRequest();
//得到表單日期值
var date = document.getElementById("birthDate");
//提交地址
var url = "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.data;
var val = xmlHttp.responseXML.getElementsByTagName("passed")[0].firstChild.data;
//設置提示信息
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>
Birth date:<input type="text" size="10" id="birthDate" />
<div id="dateMessage"></div>
</body>
</Html>
服務器端代碼,執行驗證
ValidationServlet.Java
import Javax.servlet.*;
import Javax.servlet.http.*;
import Java.io.*;
import Java.util.*;
import Java.text.SimpleDateFormat;
public class ValidationServlet extends HttpServlet {
private static final String CONTENT_TYPE = "text/Html; charset=GBK";
//Initialize global variables
public void init() throws ServletException {
}
/**
* 處理Get請求
* @param request HttpServletRequest
* @param response HttpServletResponse
* @throws ServletException
* @throws IOException
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(CONTENT_TYPE);
//得到輸出對象
PrintWriter out = response.getWriter();
//得到日期值,作為參數驗證
boolean passed = validateDate(request.getParameter("birthDate"));
response.setContentType("text/XML");
response.setHeader("Cache-control","no-cache");
String message = "You have entered an invalid date.";
if (passed){
message = "You have entered a valid date.";
}
//輸入XML格式字符串
out.println("<response>");
out.println("<passed>" + Boolean.toString(passed) + "</passed>");
out.println("<message>" + message + "</message>");
out.println("</response>");
out.close();
}
//Clean up resources
public void destroy() {
}
/**
* 驗證日期
* @param date String 日期
* @return boolean
*/
private boolean validateDate(String date){
boolean isValid = true;
if (date != null){
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
try {
formatter.parse(date);
}
catch (Exception ex) {
System.out.println(ex.toString());
isValid = false;
}
}
else{
isValid = false;
}
return isValid;
}
}