日期:2014-05-16 浏览次数:20763 次
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Validation extends HttpServlet {
private static final long serialVersionUID = 5873405129982361860L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 获取参数前, 需要设置编码
request.setCharacterEncoding("utf-8");
// 设置返回的格式为xml
// response.setContentType("text/xml;charset=utf-8");
// 设置禁止缓存
response.setHeader("Cache-Control", "no-cache, must-revalidate");
// 验证用户名是否已经存在
validate(request, response);
}
private void validate(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 设置返回的格式为xml
response.setContentType("text/xml;charset=utf-8");
PrintWriter out = response.getWriter();
String message = "";
String username = request.getParameter("username");
if("aaa".equals(username) || "bbb".equalsIgnoreCase(username)) {
System.out.println("已经存在");
message = "<result><message>用户名" + username + "已存在!</message></result>";
} else {
message = "<result><message>恭喜, 用户名" + username + "可以注册!</message></result>";
}
out.println(message);
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="/common.jsp" %>
<!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>处理返回值为xml格式</title>
<script type="text/javascript" src="${contextPath}/js/jquery-1.3.1.js"></script>
<script type="text/javascript">
// ajax引擎
var xmlHttpRequest;
// 创建ajax引擎
function getXMLHttpRequest() {
// 不同浏览器获取XMLHttpRequest对象方法不同
if(window.ActiveXObject) {
// IE
xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
} else if(window.XMLHttpRequest) {
// 火狐, google等非IE
xmlHttpRequest = new XMLHttpRequest();
}
}
// 检查用户名是否已经存在(提交数据到后台)
function checkName() {
//