1. 程式人生 > >Ajax驗證用戶名是否被註冊

Ajax驗證用戶名是否被註冊

ava ole etl doc window 操作類 throws 情況 javascrip

Ajax驗證用戶名是否被註冊

var xmlHttp;
function createXMLHttpRequest(){ // 創建XMLHttp請求對象
if(window.ActiveXObject){
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}else if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();

}
}
xmlHttp.onreadystatechange=處理方法
xmlHttp:這是XMLHttpRequest對象名稱
處理方法:這是自定義的JavaScript方法名稱
function startRequest(userName){ // 發送頁面請求
createXMLHttpRequest();
xmlHttp.onreadystatechange=handleStateChange; // 指定處理服務器響應的方法
xmlHttp.open("GET","regsiterServlet?userName="+userName,true);
xmlHttp.send(null);
}
<script type="text/javascript">
var xmlHttp;
function createXMLHttpRequest(){ // 創建XMLHttp請求對象
if(window.ActiveXObject){
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}else if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}
}
function handleStateChange(){ // 處理應答數據
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
document.getElementById(‘text‘).innerHTML=xmlHttp.responseText;
}
}
}
function startRequest(userName){ // 發送頁面請求
createXMLHttpRequest();
xmlHttp.onreadystatechange=handleStateChange;
xmlHttp.open("GET","regsiterServlet?userName="+userName,true);
xmlHttp.send(null);
}
</script>
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter(); // 獲取應答對象的字符輸出流
try {
UserDao dao = new UserDao(); // 創建數據庫操作類
String userName = request.getParameter("userName"); // 獲取請求對象的用戶名參數
if(userName==null||userName.isEmpty()){
// 返回提示信息
out.print("<font color=‘red‘>必須輸入用戶名</font>");
return;
}
boolean hasUser = dao.hasUser(userName); // 判斷數據庫是否存在指定用戶名
if (hasUser) { // 如果存在重名情況
// 返回已註冊信息
out.print("<font color=‘red‘>該用戶名已經被註冊</font>");
} else { // 否則
// 提示用戶可以註冊
out.print("<font color=‘green‘>該用戶名可以使用</font>");
}
} catch (Exception ex) {
Logger.getLogger(RegisterServlet.class.getName()).log(Level.SEVERE, null, ex);
} finally {
out.close();
}
}
public boolean hasUser(String userName) {
boolean hasUser = false; // 聲明檢查變量,false代表沒有重名用戶
Connection conn = getConn(); // 連接數據庫
if (conn != null) {
// 定義SQL查詢語句
String sql = "SELECT count(*) FROM tb_checkUser where username=?";
try {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, userName); // 設置查詢語句的參數
ResultSet rs = ps.executeQuery(); // 執行SQL查詢
if (rs.next()) {
int count = rs.getInt(1); // 獲取同名用戶數量
if (count > 0) { // 如果同名用戶數量大於0
hasUser = true; // 設置檢查變量為true,代表用戶重名
}
}
rs.close(); // 是否資源
ps.close();
conn.close();
} catch (SQLException ex) {
Logger.getLogger(UserDao.class.getName()).log(Level.SEVERE, null, ex);
}
}
return hasUser;
}

Ajax驗證用戶名是否被註冊