[英]How to write a database connection in Javascript?
我想連接到數據庫,具體取決於以.jsp
形式輸入的數據。 我不知道如何在Javascript
連接數據庫。
我的代碼如下:
<%@ page contentType="text/html; charset=iso-8859-1" language="java" %>
<html>
<head>
<script>
function validateForm()
{
if(document.frm.username.value=="srinu")
{
// conect database here
}
else
{
alert("wrong input");
document.frm.pwd.focus();
return false;
}
}
在這里,我想根據在正文中輸入的詳細信息連接數據庫。
<body>
<form name="frm" method="get" action="validateInput.jsp" onSubmit="return validateForm()">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="22%"> </td>
<td width="78%"> </td>
</tr>
<tr>
<td>UserName </td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="submit" value="Submit"></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
</form>
</body>
</html>
您無法從客戶端連接到數據庫。 JavaScript在具有非常嚴格的安全限制的瀏覽器上運行。 並且在JavaScript上保留任何連接字符串都不是一個好習慣。 不要在客戶端保留任何敏感的東西。 打電話給服務器端驗證並對其進行處理。
function validateForm()
{
if(document.frm.username.value=="srinu")
{
$.ajax({
type: 'GET',
url: 'validateuser?username=document.frm.username.value' + '&Pwd=' + document.frm.userpassword.value,
success: function (data) {
if (data=='Y')
alert('Valid User');
else
alert('Invalid User');
}, cache: false,
error: function (xhr, ajaxOptions, thrownError) {
alert('failed.');
}
});
}
}
@ user2773010很高興能提供幫助,而不是整個項目。 您需要考慮如何根據您的要求實現以下snippit。
String userName = request.getParameter("user");
String password = request.getParameter("pass");
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver") ;
con = DriverManager.getConnection("jdbc:odbc:library", "administrator", "");
stat = con.createStatement();
System.out.println("user Connected");
rs = stat.executeQuery("Select * FROM User_Master");
while(rs.next())
{
String un = rs.getString(5);
String Pwd = rs.getString(6);
if(un.equals(userName) && Pwd.equals(password))
{
session.setAttribute("username",un);
String des = "http://localhost:8080/Final_Review/review/homeuser.jsp";
response.sendRedirect(response.encodeRedirectURL(des));
break;
}
/* else
{
response.sendRedirect(response.encodeRedirectURL("http://localhost:8080/Final_Review/review/ErrorPage.jsp"));
}*/
}
stat.close();
con.close();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch(SQLException se)
{
System.out.println(se);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.