日期:2014-05-16 浏览次数:20763 次
前端页面:index.jsp
<%--
? Created by IntelliJ IDEA.
? User: wustrive_2008
? Date: 2011-3-22
? Time: 18:24:36
? To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
??? <title>myajax校验</title>
??? <script type="text/javascript" src="verify1.js"></script>
</head>
<body>
??? 用户名: <input type="text" id="username" />
??????????? <input type="button" value="提交" onclick="verify()"/>
<div id="message" style="color:red"></div>
</body>
</html>
服务器端Servlet:AJAXServlet.java及web.xml
AJAXServlet.java:
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
?* Created by IntelliJ IDEA.
?* User: wustrive_2008
?* Date: 2011-3-22
?* Time: 18:30:12
?* To change this template use File | Settings | File Templates.
?*/
public class AJAXServlet extends HttpServlet {
??? @Override
??? protected void doPost(HttpServletRequest req, HttpServletResponse resp)
??????????? throws ServletException, IOException {
????????? try{
????????????? resp.setContentType("text/html;charset=UTF-8");
????????????? PrintWriter out=resp.getWriter();
????????????? String name=req.getParameter("name");
????????????? if(name==null||name.length()==0){
????????????????? out.print("用户名不能为空!");
????????????? }else{
??????????????????? if(name.equals("wustrive_2008")){
??????????????????????? out.println("此用户名已经注册!");
??????????????????? }else{
??????????????????????? out.println("恭喜你!该用户可以注册!");
??????????????????? }
????????????? }
????????? }catch(Exception e){
?????????????????? e.printStackTrace();
??????? }
??? }
??? @Override
??? protected void doGet(HttpServletRequest req, HttpServletResponse resp)
??????????? throws ServletException, IOException {
??????? doPost(req, resp);
??? }
}
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
?????????? xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
?????????? xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
??? ??? ? http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
?????????? version="2.5">
?<servlet>
???? <servlet-name>AJAXServlet</servlet-name>
???? <servlet-class>AJAXServlet</servlet-class>
?</servlet>
?<servlet-mapping>
???? <servlet-name>AJAXServlet</servlet-name>
???? <url-pattern>/AJAXServlet</url-pattern>
?</servlet-mapping>
<welcome-file-list>
??? <welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
一,使用XMLHttpRequest对象:verify1.js
var xmlhttp;
function? verify(){
??? var userName=document.getElementById("username").value;
??? if(window.XMLHttpRequest()){
??????? xmlhttp=new XMLHttpRequest();
??????? if(xmlhttp.overrideMimeType){
??????????? xmlhttp.overrideMimeType("text/xml");
??????? }
??? }else if(wi