Wednesday, February 16, 2011

Live Availability Checking with Java


Some days I had posted an article about User name live availability checking with PHP and jquery. In this post my brother Ravi Tamadaexplained the same with Java technologies like JSP and servelts using MySQL database.

Live Availability Checking with Java.


 Download Script     Live Demo

About Author 
Ravi Tamada
Computer science engineering, Final Year
India, Twitter Profile @ravi8x
ravi8x[at]gmail.com )

You just download the script copy and paste the directory into Tomcat Webappsdirectory
Database
MySQL users table columns uid, uname, passcode.
CREATE TABLE users
(
uid INT PRIMARY KEY AUTO_INCREMENT,
uname VARCHAR(50) UNIQUE,
passcode VARCHAR(50)
);

index.jsp
$('#uname').change(function(){} - uname is the ID of the input. Using$("#uname").val() calling input field value. First checking the value string length max 3 (uname.length > 3)
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$(".uname").change(function()
{
var uname = $(this).val();
if(uname.length > 3)
{
$(".status").html("Checking availability...");
$.ajax
({
type: "POST",
url: "check",
data: "uname="+ uname,
success: function(msg)
{
$(".status").ajaxComplete(function(event, request, settings)
{
$(".status").html(msg);
});
}
});
}

else
{
$(".status").html("username shold be 3 chars");
}

});
});

</script>
<div>
<label>user name :</label>
<input type="text" class="uname"/><span class="status"></span>
</div>

check.java
Contains java code. Download link Mysql Java Connector Jar file
import java.io.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;

public class check extends HttpServlet
{
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try
{
// 9lessons is my database name
String connectionURL = "jdbc:mysql://localhost:3306/9lessons";
Connection connection = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root","root");
String uname = request.getParameter("uname");
PreparedStatement ps = connection.prepareStatement("select uname from USERS where uname=?");
ps.setString(1,uname);
ResultSet rs = ps.executeQuery();

if (!rs.next())
{
out.println("<b>"+uname+"</b> is avaliable");
}
else
{
out.println("<font color=red><b>"+uname+"</b> is already in use</font>");
}
out.println();
}
catch (Exception ex)
{
out.println("Error ->" + ex.getMessage());
}
finally 
{
out.close();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doPost(requestresponse);
}
}

No comments:

Post a Comment