0

在我的应用程序中,我使用 JSP 作为视图,servlet 作为控制器,休眠作为模型..

在该应用程序 jsp 页面中,我必须在创建具有用户名和所有字段等字段的新用户时填写表单。

现在我想使用 AJAX 代码来检查在表单中输入名称的用户名名称是否已经存在于数据库中...

任何人都可以指导我如何为此编写代码以及控制流..

我用谷歌搜索但不知道如何满足这个要求..

提前致谢

4

3 回答 3

0

在这里,您有两个用户名验证选项。

1> 客户端(用户界面)端验证 2> 服务器端验证

对于选项 1>,您需要编写 ajax 调用,该调用将向服务器发出请求并响应结果,该结果将告知使用是否有效。

对于客户端,我建议您使用 java 脚本或 jQuery。这是示例 jQuery ajax 代码。

  $.ajax({
   url: "validateUser.html?username=username",
   success:function(data){
      //YOUR CODE FOR FUTHRE ACTION FOR VALID/INVALID ACTION
   }
  });

您可以在此处参考 jQuery ajax 。对于选项 2>,在服务器端进行验证...

您可以在提交表单时验证用户名。

您可以通过 request.getParamter("userName"); 检索值 并检查数据库是否已经存在或不存在。

问候,贡扬。

于 2012-10-10T10:27:03.283 回答
0

在 Jsp 中

<script type="text/javascript">
    function VerifyUsername()
    {
        //alert("In Verify Method");
        var name=document.getElementById("username").value;
        //alert(name);
        var xmlhttp;
        if (window.XMLHttpRequest)
        {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp=new XMLHttpRequest();
            //alert("http");
         }
        else
        {// code for IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            alert("http active");
        }
        xmlhttp.onreadystatechange=function()
        {
            //alert("in Function()");
            if (xmlhttp.readyState==4 && xmlhttp.status==200)
            {
                try
                {
                    //alert("In Try");
                    document.getElementById("errorpass").innerHTML=xmlhttp.responseText;
                    /*var response = xmlhttp.responseText;
                    alert(response);
                    if(response.toString()=='notmatch')
                    {
                        alert("Ok");
                        document.getElementById("errorpass").innerHTML ="OK";
                    }
                    if(response =='match')
                    {
                        alert("Not Ok");
                        document.getElementById("errorpass").innerHTML ="Take Other Name.";
                    }*/
                }
                catch(ex)
                {
                    alert("Exception in function "+ex);
                }
            }
        }
        //xmlhttp.open("POST","servlet/UsernamePresence_Serv?UserId"+name,true);
        xmlhttp.open("POST","servlet/UsernamePresence_Serv?"+name,true);
        var params = "UserId="+name;
        xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        xmlhttp.setRequestHeader("Content-length", params.length);
        xmlhttp.setRequestHeader("Connection", "close"); 
        xmlhttp.send(params);
    }
</script>

在 Servlet 中

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    try
    {
        Session session=Hibernate_Class.sessionObject();
        String userID=null;
        userID = request.getParameter("UserId");

        login_model loginModel_Obj=new login_model();
        loginModel_Obj._Name=userID;
        System.out.print("at "+userID);
        boolean username_bool=Hibernate_Class.usernamePresence(loginModel_Obj, session);

        if (username_bool)
        {
            out.println("Username Present In Database");
        }
        else
        {
            out.println("Username Not Present In Database");
        }

    }
    finally{}
    out.close();
}
于 2012-10-11T15:07:34.390 回答
-1

在下面的代码中,只需用您的 Hibernate Code 替换 JDBC 代码。

JSP

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://
www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=iso-8859-1" />
<title> - User Login</title>

<style type="text/css">

#marqueecontainer{
position: relative;
width: 150px; /*marquee width */
height: 163px; /*marquee height */
/*background-color: white;*/
overflow: hidden;
/*border: 3px solid orange;
padding: 2px;
padding-left: 4px;*/

}

</style>
</head>
<script language="javascript">

var mWindow="windows";
var objLogRequest;



function chekUserId()
{
try
{
if(document.getElementById("userID").value=="")
{
alert(" You have not entered Username. ");
return 0;
}
if(document.getElementById("userPass").value=="")
{
alert("You have not entered Password.");
return 0;
}

var userId = document.getElementById("userID").value;
var userPass = document.getElementById("userPass").value;

//alert("userId:->"+userId);
//alert("userPass:->"+userPass);
serUrl ='/servlet/UserLogin?userID='+userId
+'&userPass='+userPass+'&randomNum='+Math.random()*Math.random();
//alert("serUrl:->"+serUrl);
if(window.ActiveXObject)
{
objLogRequest = new ActiveXObject('Microsoft.XMLHTTP');
//alert("Windos Browser");
}
else
{
objLogRequest = new XMLHttpRequest();
mWindow = "nonWindows";
}
if(objLogRequest)
{
//alert("objAddRequest 1");
objLogRequest.onreadystatechange = sendLogInfo;
//alert("objAddRequest 2");
objLogRequest.open('Get',serUrl);
//alert("objAddRequest 3");
if(mWindow=='nonWindows')
{
objLogRequest.send('');
}
else
{
//alert("before send ");
objLogRequest.send();
//alert("after send ");
}
}

}// end try
catch(e)
{
alert("Exception in chekUserId function "+e);
}

}
function sendLogInfo()
{
try
{
//alert('object state :-> '+objLogRequest.readyState)
if(objLogRequest.readyState==4)
{
if(objLogRequest.status==200)
{
var response = objLogRequest.responseText;
//alert('response :-> '+response)

if(response =='notmatch')
{

document.getElementById("errorpass").innerHTML ="Username and
password do not match.(You provided
"+document.getElementById("userID").value+" )";
document.getElementById("userPass").value="";

}
if(response =='match')
{
alert('user valid');
}
}
}
}
catch(ex)
{
alert("Exception in sendInfo function "+ex);
}
}

</script>
<body marginheight="0" marginwidth='0' topmargin='0'
bottommargin='0'leftmargin='0' class="body">
<table width="751" border="0" align="center" cellpadding="0"
cellspacing="0">
<tr>
<td bgcolor="#000099"><table width="751" border="0"
cellspacing="1" cellpadding="0">
<tr>
<td bgcolor="#FFFFFF"><table width="751" border="0"
cellspacing="0" cellpadding="0">
<tr>
<td>
</td>
</tr>
<tr>
<td height="25" align="left" valign="middle"
bgcolor="#C7C7C7" class="plan-a-trip"><span class="welcometext"></
span></td>
</tr>
<tr>
<td height="10" align="left" valign="top"></td>
</tr>
<tr>
<td><table width="751" border="0" cellspacing="0"
cellpadding="0">
<tr>
<td width="10" align="left" valign="middle">&nbsp;</
td>
<td width="150" align="left" valign="top">
</td>
<td width="10" align="left" valign="top"></td>
<td width="571" height="270" align="left"
valign="top" bgcolor="#999999"><table width="571" border="0"
cellspacing="1" cellpadding="0">
<tr>
<td width="579" height="476" align="left"
valign="top" bgcolor="#FFFFFF">
<table width="571" height="391" border="0" cellpadding="0"
cellspacing="0">
<form name='loginform' method='get' action='/servlet/UserLogin'
onSubmit="return submit(document.loginform);" >
<tr>
<td width="25" rowspan="11" align="left"
valign="top">&nbsp;</td>
<td width="459" height="20" align="left"
valign="top">&nbsp;</td>
<td width="20" rowspan="11" align="left"
valign="top">&nbsp;</td>
</tr>
<tr>
<td height="16" align="left"
valign="middle"><img src="/image/PlanATrip/UserLogin/member_login.jpg"
width="120" height="13" /></td>
</tr>
<tr>
<td height="10" align="left"
valign="middle">&nbsp;</td>
</tr>
<tr>
<td height="5" align="left" valign="top"></td>
</tr>
<tr>
<td height="100" align="left"
valign="top"><table width="479" height="115" border="0"
cellpadding="0" cellspacing="0">
<tr>
<td width="85" align="left"
valign="middle" class="text">Username</td>
<td width="10" rowspan="6" align="left"
valign="top">&nbsp;</td>
<td width="376">
<input id="userID" name="userID"
type="text" class="inputtext" maxLength="25"/> </td>
</tr>
<tr>
<td height="5" align="left"
valign="middle"></td>
<td height="5" align="left" valign="top"></
td>
</tr>
<tr>
<td align="left" valign="middle"
class="text">Passward</td>
<td><input id="userPass" name="userPass"
type="password" maxlength="15" class="inputtext" /></td>
</tr>
<tr>
<td height="5" align="left"
valign="middle"></td>
<td height="5" align="left" valign="top"
class="wrongpass" id="errorpass">&nbsp;</td>
</tr>

<tr>
<td align="left" valign="middle">&nbsp;</
td>
<td><input name="loginBut" type="button"
id="loginBut" class="searchButton" value="Login"
onclick="chekUserId()"/></td>
</tr>
<tr>
<td align="left" valign="middle">&nbsp;</
td>
<td ><a href="/servlets/Registration.html"
class="fyp">New User Sign Up</a></td>
</tr>
</table></td>
</tr>

<tr>
<td height="10" align="left"
valign="top">&nbsp;</td>
</tr>
<tr>

</tr>
</form>
</table></td>
</tr>
</table></td>
<td width="10" align="left" valign="middle">&nbsp;</
td>
</tr>

</table></td>
</tr>
<tr>
<td></td>
</tr>
</table></td>
</tr>
</table></td>
</tr>
</table>
</body>
</html>

小服务程序代码

import java.io.*;
import java.sql.*;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;

public class UserLogin extends HttpServlet
{

public String DBUrl = "jdbc:mysql://127.0.0.1:3306/
databasename";

public void init ()
{
//getCon();
System.out.println("UserLogin called");
}



public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{


res.setContentType("text/html");

PrintWriter out = res.getWriter();

ResultSet rs=null;

Connection con = null;
Statement stm=null;



//Vector userId;

String userID=null,userPass=null,currentDate=null;
userID = req.getParameter("userID");
userPass = req.getParameter("userPass");
HttpSession session = req.getSession(true);


try
{

con = pool.getCon();
stm = con.createStatement();
//System.out.println("connect");

////chek user ID Start ***//////
String querySelctId = "select count(*)user from userinfo where
UserId='"+userID+"'AND UserPassword='"+userPass+"';";

rs = stm.executeQuery(querySelctId);

//System.out.println("4");
int count = 0
try{
count = rs.getString(1);
}catch(SQLException sqlEx){
System.out.println("sqlEx");
}catch(Exception ex){
System.out.println("Ex");
}

if(count==1)
{
System.out.println(userID+":-> Login");

out.print("match");
}
else
{
out.print("notmatch");

}


}

catch (SQLException sqle)
{
System.out.println("SQLException");
System.out.println(sqle);
//res.sendRedirect("/servlets/RegistrationFail.html");

}
catch (Exception ex)
{
System.out.println("Exception");
System.out.println(ex);
res.sendRedirect("/servlets/ErrorPage.htm");

}
finally
{
try
{
if(con != null)
{
System.out.print("UserLogin Servlet release:-> ");
pool.releaseConnection(con);
rs.close();
stm.close();
out.flush();
out.close();
}
}
catch(Exception Ex)
{
System.out.println(" Exception in release the connection ");
System.out.println(Ex);
}

}
}

public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException, IOException
{
doPost(req,res);
}





public Connection getCon()
{
Connection con = null;

try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(DBUrl,"root","");
databaseMetaData = con.getMetaData();
stm = con.createStatement();
}catch(java.lang.ClassNotFoundException e)
{
System.err.print("ClassNotFoundException: ");

System.err.println(e.getMessage());
}catch (SQLException sqle)
{
System.out.println("SQLException");
System.out.println(sqle);
}catch (Exception ex)
{
System.out.println("Exception");
System.out.println(ex);
}
return con;
}
}
于 2012-10-10T10:19:14.910 回答