ajax 商務邏輯:一個標準的輸入框,要求輸入日期格式的文本,符合要求用綠字顯示資訊,否則用紅字提示。
頁面: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;
}
}