Check username availability using Java, JSP, AJAX, MySQL, JDBC, Servlet


Hey guys, today we are gonna be developing the username availability application based on the real world scenario and using the technologies which are used across almost all the major IT firms.

Before we begin writing the code I'd assume that you guys have following software installed.

  1. Eclipse IDE
  2. Tomcat app server
  3. MySQL Database


Alright, first of all we are going to start the DB and will create the database and the table. After that we can enter some test values. Check the script below.
MySQL Script:
create database students;

create table users(
 uid int primary key 
        auto_increment,
 uname varchar(20) unique
 );

INSERT INTO `students`.`users` 
(`uid`, `uname`) VALUES ('1', 
'Amjad');INSERT INTO 
`students`.`users` (`uid`, 
`uname`) VALUES ('2', 'Amzi');


Create a dynamic web project in your IDE workspace and the project structure should look something like this.

Next are going to create the view using jsp, the view will consist of a simple text box which will check if the input string value is 3 character long or not. If yes then it will go ahead and make a query and will check the availability of the username.

index.jsp


Username Availability


 


 
 


Now, we are going to write a servlet which will create a database connection and make a query to it.
CheckAvailability.java
package com.amzi.servlets;

import java.io.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;

public class CheckAvailability extends HttpServlet {

 private static final long serialVersionUID = -734503860925086969L;

 protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {

            String connectionURL = "jdbc:mysql://localhost:3306/students"; // students is my database name
            Connection connection = null;
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            connection = DriverManager.getConnection(connectionURL, "root", "password");
            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(""+uname+" is avaliable");
            }
            else{
            out.println(""+uname+" is already in use");
            }
            out.println();

        } catch (Exception ex) {
            out.println("Error ->" + ex.getMessage());
        } finally {
            out.close();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }
}


Also, we can configure the deployment descriptor as follows.
web.xml


    
        check
        com.amzi.servlets.CheckAvailability
    
    
        check
        /check
    
    
        
            30
        
    
    
        index.jsp
        
    


Note: In addition to these code we also need jquery library and mysql connector jar file. Just in case you are unable to find those, you may click here to get the complete source code.

Now, we are all set to deploy and test the code on the server. We can hit the below url
http://localhost:8080/UserAvailability/
And, the page will look something like this

22 comments:

  1. Replies
    1. alama sundari nan allaka vantha sundari

      Delete
  2. thanks a lot, exactly like i'm looking for.

    ReplyDelete
  3. Hi.
    Great tutorial, but I have one problem
    Could you tell me why text in my status class (span) shows when input losts focus ?

    Thanks in advance

    ReplyDelete
    Replies
    1. good question, but you have to find the answers all by yourself, otherwise how will you learn.

      Delete
  4. great !!!!!!!! look..suggest me how to retrieve a list of images from database

    ReplyDelete
    Replies
    1. you should ask politely only then someone will be ready to help you. hara hara maha deveki

      Delete
  5. It is not displaying msg, only showing checking avaliablity

    ReplyDelete
    Replies
    1. You may have imported jquery in your design also. So, the jquery of this code and the jquery of the design gets conflicted..Just comment the jquery import statement in your design and try once.

      Delete
  6. same as praveen. all it shows is "checking availability..." and doesn't show whether the user is available like in the image. :(

    ReplyDelete
    Replies
    1. just change this code :
      $.ajax({
      type: "POST",
      url: "check",
      data: "uname="+ uname,

      with :
      $.ajax({
      type: "POST",
      url: "CheckAvalability",
      data: "uname="+ uname,

      Delete
    2. $.ajax({
      type: "POST",
      url: "CheckAvailability",
      data: "uname="+ uname,

      Delete
    3. Mine still now working.
      Ain't url should be as web.xml?
      I'm new to these stuff

      Delete
    4. You may have imported jquery in your design also. So, the jquery of this code and the jquery of the design gets conflicted..Just comment the jquery import statement in your design and try once.

      Delete
  7. thanks for the post. by the way i have also written a similar post on my php blog

    ReplyDelete
  8. thanks a lot exactly what i am looking for

    ReplyDelete
  9. usually i dont comment on pages like this , but when i do comment I'll make sure that I made my point clear and i said evrything I'm willing to. I'm from india, born in jan 23 1993. i am a good boy. I've never used cigaratte or alchohol. Thanks to jesus, follow the path of jesus you'll find your answers. if jesus gives you lemon, be very happy because he usually won't do that and do not put lemon juice with that lemon. try to sell the lemon in online websites you may get some extras money, with that moeny you can buy some apple and milk and have apple milk shake. if you don't know how to prepare milk shake don't worry jesus is the answer take a glass, the glass should be empty, pour milk in it, do not drink the milk now it self , cut apple into pieces and add it to the milk add some ice cubes and stir. there you go. now drink it'll taste better than lemon juice. like wise there is a demon within everyone, sell that demon and buy a angel. just because angel is girl do not try to abuse her, jesus will punish you. may the gods be on your side, but don't take to much advantage from god.

    ReplyDelete
  10. I have read your blog its very attractive and impressive. I like it your blog.

    Java Training in Chennai Core Java Training in Chennai Core Java Training in Chennai

    Java Online Training Java Online Training JavaEE Training in Chennai Java EE Training in Chennai

    ReplyDelete
  11. This comment has been removed by the author.

    ReplyDelete