使用Ajax完成验证

     在看书的同时,写的小例子都想把他给保存下来,供以后复习用。

一个日期验证的例子,也许不完美,但是逻辑还是比较清晰的:

1.validation.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>用户验证</title>
<script type="text/javascript">
		var xmlHttp;
		function createXHR()
		{
			if(window.ActiveXObject)
			{
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			}else if(window.XMLHttpRequest)
			{
				xmlHttp = new XMLHttpRequest();
			}
		}		
		function setMessage (message ,isValid)
		{
			var messageArea = document.getElementById("dateMessage");
			var fontColor = "red";
			if(isValid=="true")
			{
				fontColor = "green";
			}			
			messageArea.innerHTML="<font color="+fontColor+">"+message+"</font>";
		}		
		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 validate()
		{
			createXHR();
			var date = document.getElementById("birthDate");
			var url = "ValidationServlet?";
			url=url+"birthDate="+escape(date.value);
			xmlHttp.onreadystatechange=callBack;
			xmlHttp.open("GET", url, true);			
			xmlHttp.send(null);
		}
</script>
</head>
<body style="background-color:#ffccff">
	<h1>Ajax Validation Example</h1>
	Birth Date :<input type="text" size="10" id="birthDate" onchage="validate()">
	<input type="button" οnclick="validate()"/>
	<div id="dateMessage"></div>
</body>
</html>


2.ValidationServlet.java

package com.wch.ajax.servlet;

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import javax.servlet.*;
import javax.servlet.http.*;

public class ValidationServlet extends HttpServlet {    
    
    /** Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        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.";
        }
        out.println("<response>");
        out.println("<passed>" + Boolean.toString(passed) + "</passed>");
        out.println("<message>" + message + "</message>");
        out.println("</response>");
        out.close();
     }
    
    /**
     * Checks to see whether the argument is a valid date.
     * A null date is considered invalid. This method
     * used the default data formatter and lenient
     * parsing.
     *
     * @param date a String representing the date to check
     * @return message a String represnting the outcome of the check
     */
    private boolean validateDate(String date) {
        
        boolean isValid = true;
        if(date != null) {
            SimpleDateFormat formatter= new SimpleDateFormat("MM/dd/yyyy");
            try {
                formatter.parse(date); 
            } catch (ParseException pe) {
                System.out.println(pe.toString());
                isValid = false;
            }
        } else {
            isValid = false;
        }
        return isValid;
    }
}



3.web.xml


<servlet>
    <servlet-name>ValidationServlet</servlet-name>
    <servlet-class>com.wch.ajax.servlet.ValidationServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ValidationServlet</servlet-name>
    <url-pattern>/ValidationServlet</url-pattern>
  </servlet-mapping>

4.运行结果:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值