我們可以在Java中建立一個AJAX範例,用於檢查資料庫中是否存在給定的電子郵件ID。
使用Java中的AJAX建立電子郵件查詢器範例的步驟
需要按照以下步驟操作:
在此頁面中,我們建立了一個表單,該表單用於獲取輸入以查詢電子郵件。當單擊檢查可用性按鈕時,它會告知電子郵件ID是否可用。
檔案:index.html
<!DOCTYPE html>
<html>
<head>
<title>Email Finder Example</title>
<script>
var request;
function sendInfo() {
var email = document.vinform.email.value;
var url = "emailfinder.jsp?email=" + email;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
try {
request.onreadystatechange = getInfo;
request.open("GET", url, true);
request.send();
} catch (e) { alert("Unable to connect to server"); }
}
function getInfo() {
if (request.readyState == 4) {
var val = request.responseText;
document.getElementById('mylocation').innerHTML = val;
}
}
</script>
</head>
<body>
<marquee>
<h1>AJAX Email Checker Example</h1>
</marquee>
<form name="vinform">
<input type="email" name="email" placeholder="enter email" />
<input type="button" onclick="sendInfo()" value="Check Availability" />
<span id="mylocation"></span>
</form>
</body>
</html>
建立伺服器端頁面以處理請求
在這個jsp頁面中,編寫資料庫程式碼來搜尋電子郵件。
<%@ page import="java.sql.*" %>
<%
String email=request.getParameter("email");
if(email.contains("@")&&email.contains(".")){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
PreparedStatement ps=con.prepareStatement("select * from user100 where email=?");
ps.setString(1,email);
ResultSet rs=ps.executeQuery();
if(rs.next()){
out.print("Unavailable! <img src='unchecked.gif'/>");
}else{
out.print("Available! <img src='checked.gif'/>");
}
}catch(Exception e){
out.print(e);
}
}else{
out.print("Invalid email!");
}
%>