How to Create Username Availability Check Webservice using REST?

In this post, I will be discussing about how to create username availability check webservice using RESTful webservice.

Are you new to RESTful webservice? Please take a quick look at our article on Introduction to RESTful webservice which will help you in creating it with much ease.

Do follow below steps to create RESTful webservice for checking username availability:

JEE webapp creation involves below steps:

  1. Configure MySQL DB and Table
  2. Create RESTful Webservice using Jersey

You can download source code from here if you don’t want to create Application from scratch, otherwise please proceed with below listings.



MySQL DB and Table

Do follow below steps to create MySQL DB and Table.

Create MySQL DB and Table:

  1. Create database called ‘users’ in phpMyAdmin or create it through command:
    create database users
  2. Select database users in phpMyAdmin or select it through command:
    use users
  3. Create table called ‘useraccount’ in phpMyAdmin or through command by pasting below SQL script in SQL Query box:
    CREATE TABLE IF NOT EXISTS `useraccount` (
      `userid` int(11) NOT NULL AUTO_INCREMENT,
      `username` varchar(12) NOT NULL,
      PRIMARY KEY (`userid`)
    )

Jersey – RESTful Webservice

Am going to use Jersey framework to design RESTful webservice.

Do follow the below steps to create RESTful webservice:

  1. Goto https://jersey.java.net/download.html and download Jersey 1.18 ZIP bundle as shown below:Download JerseyUnzip the bundle, you can see list of Jars under lib folder as shown below:

    Jersey JARS

  2. Create Dynamic web project in Eclipse as shown below:Choose File>>New>>Dynamic Web Project

    Create Dynamic Web Project - Step 1

    Enter project name as ‘usernamecheckws’ and Click Finish

    Create Dynamic Web Project - Step 2

  3. Add unzipped Jersey library JARs to WEB-INF/lib folderJersey JARs
  4. Register Jersey as Servlet dispatcher by adding below code into web.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
      <display-name>usernamecheckws</display-name>
      <servlet>
        <servlet-name>Jersey REST Service</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
          <param-name>com.sun.jersey.config.property.packages</param-name>
          <param-value>com.prgguru.jersey</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
      </servlet>
      <servlet-mapping>
        <servlet-name>Jersey REST Service</servlet-name>
        <url-pattern>/*</url-pattern>
      </servlet-mapping>
    </web-app>
  5. Create a package called ‘com.prgguru.jersey’ under src folder

    Package

  6. Create a class called ‘Constants.java’ under the package ‘com.prgguru.jersey’ and add below code to it:
    Constants class holds application constants like DB class, DB username etc.,
    Constants.java
    package com.prgguru.jersey;
    //Change these parameters according to your DB
    public class Constants {
    	public static String dbClass = "com.mysql.jdbc.Driver";
    	private static String dbName= "users";
    	public static String dbUrl = "jdbc:mysql://localhost:3306/"+dbName;
    	public static String dbUser = "root";
    	public static String dbPwd = "password";
    }
  7. Create a class called ‘DBConnection.java’ under the package ‘com.prgguru.jersey’ and add below code to it:
    DBConnection class performs DB related operations like Opening DB connection, Inserting records and Selecting records from Table.
    DBConnection.java
    package com.prgguru.jersey;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    public class DBConnection {
    	/**
    	 * Method to create DB Connection
    	 * 
    	 * @return
    	 * @throws Exception
    	 */
    	@SuppressWarnings("finally")
    	public static Connection createConnection() throws Exception {
    		Connection con = null;
    		try {
    			Class.forName(Constants.dbClass);
    			con = DriverManager.getConnection(Constants.dbUrl, Constants.dbUser, Constants.dbPwd);
    		} catch (Exception e) {
    			throw e;
    		} finally {
    			return con;
    		}
    	}
        /**
         * Method to check whether username already exists in DB or not
         * 
         * @param uname
         * @param pwd
         * @return
         * @throws Exception
         */
    	public static boolean checkUnameAvailability(String uname) throws Exception {
    		boolean isUnameAvailable = true;
    		Connection dbConn = null;
    		try {
    			try {
    				dbConn = DBConnection.createConnection();
    			} catch (Exception e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    			Statement stmt = dbConn.createStatement();
    			String query = "SELECT * FROM useraccount WHERE username = '" + uname + "'" ;
    			ResultSet rs = stmt.executeQuery(query);
    			// Check whether uname exists in DB
    			while (rs.next()) {
    				isUnameAvailable = false;
    			}
    		} catch (SQLException sqle) {
    			throw sqle;
    		} catch (Exception e) {
    			// TODO Auto-generated catch block
    			if (dbConn != null) {
    				dbConn.close();
    			}
    			throw e;
    		} finally {
    			if (dbConn != null) {
    				dbConn.close();
    			}
    		}
    		return isUnameAvailable;
    	}
    }
  8. Create a class called ‘Utility.java’ under the package ‘com.prgguru.jersey’ and add below code to it:
    Utility class has utility methods to perform Null check, contruct JSON etc.,
    Utility.java
    package com.prgguru.jersey;
    
    import org.codehaus.jettison.json.JSONException;
    import org.codehaus.jettison.json.JSONObject;
    
    public class Utitlity {
    	/**
    	 * Null check Method
    	 * 
    	 * @param txt
    	 * @return
    	 */
    	public static boolean isNotNull(String txt) {
    		return txt != null && txt.trim().length() >= 0 ? true : false;
    	}
    
    	/**
    	 * Method to construct JSON
    	 * 
    	 * @param tag
    	 * @param status
    	 * @return
    	 */
    	public static String constructJSON(String tag, boolean status) {
    		JSONObject obj = new JSONObject();
    		try {
    			obj.put("tag", tag);
    			obj.put("status", new Boolean(status));
    		} catch (JSONException e) {
    			// TODO Auto-generated catch block
    		}
    		return obj.toString();
    	}
    
    	/**
    	 * Method to construct JSON with Error Msg
    	 * 
    	 * @param tag
    	 * @param status
    	 * @param err_msg
    	 * @return
    	 */
    	public static String constructJSON(String tag, boolean status,String err_msg) {
    		JSONObject obj = new JSONObject();
    		try {
    			obj.put("tag", tag);
    			obj.put("status", new Boolean(status));
    			obj.put("error_msg", err_msg);
    		} catch (JSONException e) {
    			// TODO Auto-generated catch block
    		}
    		return obj.toString(); 
    	}
    
    }
  9. Create a class called UsernameChecker.java under the package ‘com.prgguru.jersey’ and add below code to it.
    UsernameChecker class is the REST resource which checks whether the username sent from client application exists in DB or not. Based on that, JSON is composed and returned back to Client application.

    UsernameChecker.java

    package com.prgguru.jersey;
    
    import javax.ws.rs.GET;
    import javax.ws.rs.Path;
    import javax.ws.rs.Produces;
    import javax.ws.rs.QueryParam;
    import javax.ws.rs.core.MediaType;
    //Path: http://localhost/<appln-folder-name>/unamechecker
    @Path("/unamechecker")
    public class UsernameChecker {
    	// HTTP Get Method
    	@GET 
    	// Path: http://localhost/<appln-folder-name>/unamechecker/docheck
    	@Path("/docheck")
    	// Produces JSON as response
    	@Produces(MediaType.APPLICATION_JSON) 
    	// Query parameters : http://localhost/<appln-folder-name>/unamechecker/docheck?username=username1
    	public String doUnameCheck(@QueryParam("username") String uname){
    		String response = "";
    		if(checkUnameExists(uname)){
    			response = Utitlity.constructJSON("unamecheck",true);
    		}else{
    			response = Utitlity.constructJSON("unamecheck", false, "Someone already has that username. Try another?");
    		}
    	return response;		
    	}
    
    	/**
    	 * Method to check whether the entered credential is valid
    	 * 
    	 * @param uname
    	 * @param pwd
    	 * @return
    	 */
    	private boolean checkUnameExists(String uname){
    		System.out.println("Inside checkCredentials");
    		boolean result = false;
    		if(Utitlity.isNotNull(uname) ){
    			try {
    				result = DBConnection.checkUnameAvailability(uname);
    			} catch (Exception e) {
    				// TODO Auto-generated catch block
    				result = false;
    			}
    		}else{
    			result = false;
    		}
    
    		return result;
    	}
    
    }
  10. Deploy the web application:Right click on the project ‘usernamecheckws’ >> Run As >> Run on Server

Code Dissection

Here are the important annotations in Jersey.

Annotation Description
@PATH(your_path) Sets the path to base URL + /your_path. The base URL is based on your application name, the servlet and the URL pattern from the web.xml configuration file.
@POST Indicates that the following method will answer to an HTTP POST request.
@GET Indicates that the following method will answer to an HTTP GET request.
@PUT Indicates that the following method will answer to an HTTP PUT request.
@DELETE Indicates that the following method will answer to an HTTP DELETE request.
@Produces(MediaType.TEXT_PLAIN[, more-types]) @Produces defines which MIME type is delivered by a method annotated with @GET. In the example text (“text/plain”) is produced. Other examples would be “application/xml” or “application/json”.
@Consumes(type[, more-types]) @Consumes defines which MIME type is consumed by this method.
@PathParam Used to inject values from the URL into a method parameter. This way you inject, for example, the ID of a resource into the method to get the correct object.

UsernameChecker.java

This class has a method called ‘doUnameCheck’ which is the REST resource, that accepts query parameter as parameters and produce JSON as the response. Query parameter is Username that is used to check in DB if it exists or not.

URL path to the method ‘doUnameCheck’ is illustrated in the below image:

Code Dissection

Install Chrome Advanced REST client extension for Testing

Chrome Advanced REST client extension provides an easy way to test the REST API. It provides lot of options like adding request headers, adding request parameters, changing HTTP method by hitting an url. Install Advanced REST client extension in chrome browser and once you installed it you can find it in chrome Apps or an icon at the top right corner.

Username Check

URL for logging in the User is http://192.168.2.4:9999/usernamecheckws/unamechecker/docheck?username=AdminGuru. Make sure you changed the IP address to your LAN IP address.

Here is the video demo of Testing I performed using Chrome Restful client:


Download Source Code

Entire project is zipped and is available for download. Unzip the downloaded project and to import the project into eclipse, launch eclipse >> File >> Import.. >> Choose downloaded project(How to import android project in eclipse).

Download Source Code

*apk in Android  is the installation file similar to exe in windows.

I have created simple Android application to consume this Webservice to perform Username availability check from within the Android application. I would recommend you to take a look at it to understand how to consume the webservice.

Username Availability Check – Android Application | Using Java RESTful Webservice

If you feel this article is helpful and interesting please spread a word about it to your friends and colleagues by sharing the article in Facebook or Twitter.

Share      

You are always welcome to provide your comments and feedback from here.

Author: Udhay

Share This Post On

Pin It on Pinterest

Shares