页面: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" οnchange="validate();"/>
<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;
}
}
}