Android Restful Webservice Tutorial – How to create RESTful webservice in Java – Part 2

Android Restful Webservice Tutorial – How to create RESTful webservice in Java – Part 2

In the Android RESTFul tutorial series , I am discussing about creating and invoking RESTful webservice in Android applications.

In this particular post, I am going to discuss about how to create RESTful webservice using Java.

If you are new to RESTful webservice, I would recommend you to take a look at Introduction to RESTful webservice

This tutorial series will be published as three parts:

How to create RESTFul webservice in Java?

In this post, I will be discussing about creating RESTful webservice in Java and in the next post will be discussing how to consume RESTful webservice we are about to create in Android application.

Here is the quick overview of the JEE webapp which we are going to create:

Application Flow

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:
    1
    create database users
  2. Select database users in phpMyAdmin or select it through command:
    1
    use users
  3. Create table called ‘user’ in phpMyAdmin or through command by pasting below SQL script in SQL Query box:
    1
    2
    3
    4
    5
    6
    7
    CREATE TABLE IF NOT EXISTS ` user ` (
       ` name ` varchar (50) NOT NULL ,
       `username` varchar (50) NOT NULL ,
       ` password ` varchar (50) NOT NULL ,
       `register_dt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ,
       PRIMARY KEY (`username`)
    )

  

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 ‘useraccount’ 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
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    <? xml version = "1.0" encoding = "UTF-8" ?>
       < display-name >useraccount</ 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
    1
    2
    3
    4
    5
    6
    7
    8
    9
    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
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    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 uname and pwd combination are correct
          *
          * @param uname
          * @param pwd
          * @return
          * @throws Exception
          */
         public static boolean checkLogin(String uname, String pwd) throws Exception {
             boolean isUserAvailable = false ;
             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 user WHERE username = '" + uname
                         + "' AND password=" + "'" + pwd + "'" ;
                 //System.out.println(query);
                 ResultSet rs = stmt.executeQuery(query);
                 while (rs.next()) {
                     //System.out.println(rs.getString(1) + rs.getString(2) + rs.getString(3));
                     isUserAvailable = true ;
                 }
             } 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 isUserAvailable;
         }
         /**
          * Method to insert uname and pwd in DB
          *
          * @param name
          * @param uname
          * @param pwd
          * @return
          * @throws SQLException
          * @throws Exception
          */
         public static boolean insertUser(String name, String uname, String pwd) throws SQLException, Exception {
             boolean insertStatus = false ;
             Connection dbConn = null ;
             try {
                 try {
                     dbConn = DBConnection.createConnection();
                 } catch (Exception e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
                 }
                 Statement stmt = dbConn.createStatement();
                 String query = "INSERT into user(name, username, password) values('" +name+ "'," + "'"
                         + uname + "','" + pwd + "')" ;
                 //System.out.println(query);
                 int records = stmt.executeUpdate(query);
                 //System.out.println(records);
                 //When record is successfully inserted
                 if (records > 0 ) {
                     insertStatus = true ;
                 }
             } catch (SQLException sqle) {
                 //sqle.printStackTrace();
                 throw sqle;
             } catch (Exception e) {
                 //e.printStackTrace();
                 // TODO Auto-generated catch block
                 if (dbConn != null ) {
                     dbConn.close();
                 }
                 throw e;
             } finally {
                 if (dbConn != null ) {
                     dbConn.close();
                 }
             }
             return insertStatus;
         }
    }
  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.,

    [pglinkadssmall1]

    Utility.java

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    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) {
             // System.out.println("Inside isNotNull");
             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 Register.java under the package ‘com.prgguru.jersey’ and add below code to it.
    Register class is the REST resource for registering the Users. User details sent from Android application will be inserted into DB after performing necessary checks.
    Register.java
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    package com.prgguru.jersey;
     
    import java.sql.SQLException;
     
    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 ( "/register" )
    public class Register {
         // HTTP Get Method
         @GET
         // Path: http://localhost/<appln-folder-name>/register/doregister
         @Path ( "/doregister"
         // Produces JSON as response
         @Produces (MediaType.APPLICATION_JSON)
         // Query parameters are parameters: http://localhost/<appln-folder-name>/register/doregister?name=pqrs&username=abc&password=xyz
         public String doLogin( @QueryParam ( "name" ) String name, @QueryParam ( "username" ) String uname, @QueryParam ( "password" ) String pwd){
             String response = "" ;
             //System.out.println("Inside doLogin "+uname+"  "+pwd);
             int retCode = registerUser(name, uname, pwd);
             if (retCode == 0 ){
                 response = Utitlity.constructJSON( "register" , true );
             } else if (retCode == 1 ){
                 response = Utitlity.constructJSON( "register" , false , "You are already registered" );
             } else if (retCode == 2 ){
                 response = Utitlity.constructJSON( "register" , false , "Special Characters are not allowed in Username and Password" );
             } else if (retCode == 3 ){
                 response = Utitlity.constructJSON( "register" , false , "Error occured" );
             }
             return response;
     
         }
     
         private int registerUser(String name, String uname, String pwd){
             System.out.println( "Inside checkCredentials" );
             int result = 3 ;
             if (Utitlity.isNotNull(uname) && Utitlity.isNotNull(pwd)){
                 try {
                     if (DBConnection.insertUser(name, uname, pwd)){
                         System.out.println( "RegisterUSer if" );
                         result = 0 ;
                     }
                 } catch (SQLException sqle){
                     System.out.println( "RegisterUSer catch sqle" );
                     //When Primary key violation occurs that means user is already registered
                     if (sqle.getErrorCode() == 1062 ){
                         result = 1 ;
                     }
                     //When special characters are used in name,username or password
                     else if (sqle.getErrorCode() == 1064 ){
                         System.out.println(sqle.getErrorCode());
                         result = 2 ;
                     }
                 }
                 catch (Exception e) {
                     // TODO Auto-generated catch block
                     System.out.println( "Inside checkCredentials catch e " );
                     result = 3 ;
                 }
             } else {
                 System.out.println( "Inside checkCredentials else" );
                 result = 3 ;
             }
     
             return result;
         }
     
    }
  10. Create a class called ‘Login.java’ under the package ‘com.prgugur.jersey’ and add below code to it.
    Login class is the REST resource which authenticates the Users. It gets the User credentials sent from Android application through HTTP and authenticates whether the credential is valid or not.
    Login.java
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    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 ( "/login" )
    public class Login {
         // HTTP Get Method
         @GET
         // Path: http://localhost/<appln-folder-name>/login/dologin
         @Path ( "/dologin" )
         // Produces JSON as response
         @Produces (MediaType.APPLICATION_JSON)
         // Query parameters are parameters: http://localhost/<appln-folder-name>/login/dologin?username=abc&password=xyz
         public String doLogin( @QueryParam ( "username" ) String uname, @QueryParam ( "password" ) String pwd){
             String response = "" ;
             if (checkCredentials(uname, pwd)){
                 response = Utitlity.constructJSON( "login" , true );
             } else {
                 response = Utitlity.constructJSON( "login" , false , "Incorrect Email or Password" );
             }
         return response;       
         }
     
         /**
          * Method to check whether the entered credential is valid
          *
          * @param uname
          * @param pwd
          * @return
          */
         private boolean checkCredentials(String uname, String pwd){
             System.out.println( "Inside checkCredentials" );
             boolean result = false ;
             if (Utitlity.isNotNull(uname) && Utitlity.isNotNull(pwd)){
                 try {
                     result = DBConnection.checkLogin(uname, pwd);
                     //System.out.println("Inside checkCredentials try "+result);
                 } catch (Exception e) {
                     // TODO Auto-generated catch block
                     //System.out.println("Inside checkCredentials catch");
                     result = false ;
                 }
             } else {
                 //System.out.println("Inside checkCredentials else");
                 result = false ;
             }
     
             return result;
         }
     
    }
  11. Deploy the web application:Right click on the project ‘useraccount’ >> Run As >> Run on Server

Code Dissection

Here are the important annotations in Jersey.

AnnotationDescription
@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.
@POSTIndicates that the following method will answer to an HTTP POST request.
@GETIndicates that the following method will answer to an HTTP GET request.
@PUTIndicates that the following method will answer to an HTTP PUT request.
@DELETEIndicates 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.
@PathParamUsed 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.

Login.java

This class has a method called ‘doLogin’ which is the REST resource, that accepts query parameters as parameters and produce JSON as the response. Query parameters are Username and Password that are used for Authenticating the Users.

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

Code Dissection

Register.java

This class has a method called ‘doregister’ which is the REST resource, that accepts query parameters as parameters and produce JSON as the response.

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

Code Dissection

[pglinkadssmall]

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.

Registration

URL for registering the User is http://192.168.2.4:9999/useraccount/register/doregister?name=Admin&username=admin@programmerguru.com&password=password. Make sure you changed the IP address to your LAN IP address.

Logging in

URL for logging in the User is http://192.168.2.4:9999/useraccount/register/doregister?username=admin@programmerguru.com&password=password. 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.

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 24 Comments box.

[pgwriteforus]
[pgfeedback]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值