JSP, Servlets & AJAX username validation, Image verification

K

KK

Hi!

Do anyone know the code for implementing AJAX for the username
availability check using JSP and servlets if yes please reply back

also do tell me the code for the image verification system in JSP

Thanking You

Kartikeya
 
A

amitatgroups

Hi!

Do anyone know the code for implementing AJAX for the username
availability check using JSP and servlets if yes please reply back

also do tell me the code for the image verification system in JSP

Thanking You

Kartikeya

--------------------- 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>


-------------------------------- Servlet Code
--------------

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;
}
}
 
L

Lew

KK said:
Do anyone know the code for implementing AJAX for the username
availability check using JSP and servlets if yes please reply back

Sun Java Blueprints is a great source for code patterns.
<https://blueprints.dev.java.net/ajaxcomponents.html>
also do tell me the code for the image verification system in JSP

Your requests are so vague and general. It makes it sound like you want
someone to develop something for free for you; that likely will only happen at
some expense, not for free. If you have a specific question about a topic you
tend to get more useful answers. For example, I do not know from your
question what you mean by an "image verification system".

I do know that you do not want a solution comprising only JSPs; JSPs are the
presentation component of a Web app. You will also need one or more servlets
(written as Java code, not JSPs) and a double-handful of JavaBeans. (Look up
"Model-View-Controller" ("MVC") for Web apps.)

For more Java Blueprints:
<https://bpcatalog.dev.java.net/nonav/solutions.html>
 
L

Lew

--------------------- 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>

[code sample snipped]

This example doesn't follow best practices.

It's got scriptlet in the JSP and HTML in the Java source code.

The Java code has hard-coded Strings and public non-final non-static members:
public String DBUrl = "jdbc:mysql://127.0.0.1:3306/databasename";

It uses System.out.println() and System.err.println() in Web code. (Use
logging, not console output.)

It's vulnerable to SQL injection attack because it doesn't use PreparedStatement:
String querySelctId = "select count(*)user from userinfo where UserId='"+userID+"'AND UserPassword='"+userPass+"';";

(Consider a user entry for the userID of
' or 1=1 --
where the single-quotes are very significant.)

The HTML contains tables nested within cells within tables.

(As a side note, one should not include embedded TABs in Usenet source-code
postings.)

The "log" call from the UserLogin servlet's init() method reads:
System.out.println("UserLogin called");

This message is misleading, since the usual interpretation of "calling" a
servlet is to call its service method, which isn't what's happening there.
It'd be more useful for the message to identify /which/ method in the servlet
was called. (And to be a logging call instead of a console output.)

Many variables are redundantly initialized:
String userID=null,userPass=null,currentDate=null;
userID = req.getParameter("userID");
userPass = req.getParameter("userPass");
HttpSession session = req.getSession(true);

It uses sendRedirect() where the JSP error-page mechanism would work better
(if the presentation were coming from a JSP as it should be), or failing that,
at least a RequestDispatcher.forward(), thus preventing the unnecessary
round-trip to the browser and concomitant loss of diagnostic information.
res.sendRedirect("/servlets/ErrorPage.htm");

(And "htm" as the suffix? Aside from the fact that the error page should be a
JSP, what's wrong with the suffix "html"?)

I'm very dubious about the lines:
pool.releaseConnection(con);
rs.close();
stm.close();

Most DB connection pools do not require the code to explicitly know of the
pooled nature of the connections, but just have the connection call its
close() method. The closing of the Connection would close the ResultSet and
the (not Prepared!) Statement. If you do close them explicitly, close the
ResultSet first, then the (Prepared!) Statement, then the connection.

The catch-all Exception catch blocks would be better handled by the error-page
mechanism.

Database logic should have its own layer, as should business logic. Mingling
presentation, logic, data access and navigation all in one is not robust.
 
L

Lew

Lew said:
(e-mail address removed) wrote:
It's vulnerable to SQL injection attack because it doesn't use
PreparedStatement:

(Consider a user entry for the userID of
' or 1=1 --
where the single-quotes are very significant.)

Of course, the SQL statement is syntactically invalid, so that actually will
prevent SQL injection attacks. It'll also prevent legitimate users from
logging in.
 
A

amitatgroups

--------------------- 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>

[code sample snipped]

This example doesn't follow best practices.

It's got scriptlet in the JSP and HTML in the Java source code.

The Java code has hard-coded Strings and public non-final non-static members:
public String DBUrl = "jdbc:mysql://127.0.0.1:3306/databasename";

It uses System.out.println() and System.err.println() in Web code. (Use
logging, not console output.)

It's vulnerable to SQL injection attack because it doesn't use PreparedStatement:
String querySelctId = "select count(*)user from userinfo where UserId='"+userID+"'AND UserPassword='"+userPass+"';";

(Consider a user entry for the userID of
' or 1=1 --
where the single-quotes are very significant.)

The HTML contains tables nested within cells within tables.

(As a side note, one should not include embedded TABs in Usenet source-code
postings.)

The "log" call from the UserLogin servlet's init() method reads:
System.out.println("UserLogin called");

This message is misleading, since the usual interpretation of "calling" a
servlet is to call its service method, which isn't what's happening there.
It'd be more useful for the message to identify /which/ method in the servlet
was called. (And to be a logging call instead of a console output.)

Many variables are redundantly initialized:
String userID=null,userPass=null,currentDate=null;
userID = req.getParameter("userID");
userPass = req.getParameter("userPass");
HttpSession session = req.getSession(true);

It uses sendRedirect() where the JSP error-page mechanism would work better
(if the presentation were coming from a JSP as it should be), or failing that,
at least a RequestDispatcher.forward(), thus preventing the unnecessary
round-trip to the browser and concomitant loss of diagnostic information.
res.sendRedirect("/servlets/ErrorPage.htm");

(And "htm" as the suffix? Aside from the fact that the error page should be a
JSP, what's wrong with the suffix "html"?)

I'm very dubious about the lines:
pool.releaseConnection(con);
rs.close();
stm.close();

Most DB connection pools do not require the code to explicitly know of the
pooled nature of the connections, but just have the connection call its
close() method. The closing of the Connection would close the ResultSet and
the (not Prepared!) Statement. If you do close them explicitly, close the
ResultSet first, then the (Prepared!) Statement, then the connection.

The catch-all Exception catch blocks would be better handled by the error-page
mechanism.

Database logic should have its own layer, as should business logic. Mingling
presentation, logic, data access and navigation all in one is not robust.

Thanks Lew...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,534
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top