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:
- Part 1 – Introduction to RESTful webservice
- Part 2 – How to create RESTFul webservice in Java?
- Part 3 – How to invoke RESTful webservice in Android applications?
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:
JEE webapp creation involves below steps:
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:
- Create database called ‘users’ in phpMyAdmin or create it through command:
1
createdatabaseusers - Select database users in phpMyAdmin or select it through command:
1
useusers - Create table called ‘user’ in phpMyAdmin or through command by pasting below SQL script in SQL Query box:
1234567
CREATETABLEIFNOTEXISTS `user` (`name`varchar(50)NOTNULL,`username`varchar(50)NOTNULL,`password`varchar(50)NOTNULL,`register_dt`timestampNOTNULLDEFAULTCURRENT_TIMESTAMP,PRIMARYKEY(`username`))
Jersey – RESTful Webservice
Am going to use Jersey framework to design RESTful webservice.
Do follow the below steps to create RESTful webservice:
- Goto https://jersey.java.net/download.html and download Jersey 1.18 ZIP bundle as shown below:
Unzip the bundle, you can see list of Jars under lib folder as shown below: - Create Dynamic web project in Eclipse as shown below:Choose File>>New>>Dynamic Web Project
Enter project name as ‘useraccount’ and Click Finish
- Add unzipped Jersey library JARs to WEB-INF/lib folder

- Register Jersey as Servlet dispatcher by adding below code into web.xml
1234567891011121314151617
<?xmlversion="1.0"encoding="UTF-8"?><web-appxmlns: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>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> - Create a package called ‘com.prgguru.jersey’ under src folder
- Create a class called ‘Constants.java’ under the package ‘com.prgguru.jersey’ and add below code to it:
Constants.javaConstants class holds application constants like DB class, DB username etc.,123456789
packagecom.prgguru.jersey;//Change these parameters according to your DBpublicclassConstants {publicstaticString dbClass ="com.mysql.jdbc.Driver";privatestaticString dbName="users";publicstaticString dbUser ="root";publicstaticString dbPwd ="password";} - Create a class called ‘DBConnection.java’ under the package ‘com.prgguru.jersey’ and add below code to it:
DBConnection.javaDBConnection class performs DB related operations like Opening DB connection, Inserting records and Selecting records from Table.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
packagecom.prgguru.jersey;importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.ResultSet;importjava.sql.SQLException;importjava.sql.Statement;publicclassDBConnection {/*** Method to create DB Connection** @return* @throws Exception*/@SuppressWarnings("finally")publicstaticConnection createConnection()throwsException {Connection con =null;try{Class.forName(Constants.dbClass);con = DriverManager.getConnection(Constants.dbUrl, Constants.dbUser, Constants.dbPwd);}catch(Exception e) {throwe;}finally{returncon;}}/*** Method to check whether uname and pwd combination are correct** @param uname* @param pwd* @return* @throws Exception*/publicstaticbooleancheckLogin(String uname, String pwd)throwsException {booleanisUserAvailable =false;Connection dbConn =null;try{try{dbConn = DBConnection.createConnection();}catch(Exception e) {// TODO Auto-generated catch blocke.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) {throwsqle;}catch(Exception e) {// TODO Auto-generated catch blockif(dbConn !=null) {dbConn.close();}throwe;}finally{if(dbConn !=null) {dbConn.close();}}returnisUserAvailable;}/*** Method to insert uname and pwd in DB** @param name* @param uname* @param pwd* @return* @throws SQLException* @throws Exception*/publicstaticbooleaninsertUser(String name, String uname, String pwd)throwsSQLException, Exception {booleaninsertStatus =false;Connection dbConn =null;try{try{dbConn = DBConnection.createConnection();}catch(Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}Statement stmt = dbConn.createStatement();String query ="INSERT into user(name, username, password) values('"+name+"',"+"'"+ uname +"','"+ pwd +"')";//System.out.println(query);intrecords = stmt.executeUpdate(query);//System.out.println(records);//When record is successfully insertedif(records >0) {insertStatus =true;}}catch(SQLException sqle) {//sqle.printStackTrace();throwsqle;}catch(Exception e) {//e.printStackTrace();// TODO Auto-generated catch blockif(dbConn !=null) {dbConn.close();}throwe;}finally{if(dbConn !=null) {dbConn.close();}}returninsertStatus;}} - 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
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556packagecom.prgguru.jersey;importorg.codehaus.jettison.json.JSONException;importorg.codehaus.jettison.json.JSONObject;publicclassUtitlity {/*** Null check Method** @param txt* @return*/publicstaticbooleanisNotNull(String txt) {// System.out.println("Inside isNotNull");returntxt !=null&& txt.trim().length() >=0?true:false;}/*** Method to construct JSON** @param tag* @param status* @return*/publicstaticString constructJSON(String tag,booleanstatus) {JSONObject obj =newJSONObject();try{obj.put("tag", tag);obj.put("status",newBoolean(status));}catch(JSONException e) {// TODO Auto-generated catch block}returnobj.toString();}/*** Method to construct JSON with Error Msg** @param tag* @param status* @param err_msg* @return*/publicstaticString constructJSON(String tag,booleanstatus,String err_msg) {JSONObject obj =newJSONObject();try{obj.put("tag", tag);obj.put("status",newBoolean(status));obj.put("error_msg", err_msg);}catch(JSONException e) {// TODO Auto-generated catch block}returnobj.toString();}} - Create a class called Register.java under the package ‘com.prgguru.jersey’ and add below code to it.
Register.javaRegister class is the REST resource for registering the Users. User details sent from Android application will be inserted into DB after performing necessary checks.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
packagecom.prgguru.jersey;importjava.sql.SQLException;importjavax.ws.rs.GET;importjavax.ws.rs.Path;importjavax.ws.rs.Produces;importjavax.ws.rs.QueryParam;importjavax.ws.rs.core.MediaType;//Path: http://localhost/<appln-folder-name>/register@Path("/register")publicclassRegister {// 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=xyzpublicString doLogin(@QueryParam("name") String name,@QueryParam("username") String uname,@QueryParam("password") String pwd){String response ="";//System.out.println("Inside doLogin "+uname+" "+pwd);intretCode = registerUser(name, uname, pwd);if(retCode ==0){response = Utitlity.constructJSON("register",true);}elseif(retCode ==1){response = Utitlity.constructJSON("register",false,"You are already registered");}elseif(retCode ==2){response = Utitlity.constructJSON("register",false,"Special Characters are not allowed in Username and Password");}elseif(retCode ==3){response = Utitlity.constructJSON("register",false,"Error occured");}returnresponse;}privateintregisterUser(String name, String uname, String pwd){System.out.println("Inside checkCredentials");intresult =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 registeredif(sqle.getErrorCode() ==1062){result =1;}//When special characters are used in name,username or passwordelseif(sqle.getErrorCode() ==1064){System.out.println(sqle.getErrorCode());result =2;}}catch(Exception e) {// TODO Auto-generated catch blockSystem.out.println("Inside checkCredentials catch e ");result =3;}}else{System.out.println("Inside checkCredentials else");result =3;}returnresult;}} - Create a class called ‘Login.java’ under the package ‘com.prgugur.jersey’ and add below code to it.
Login.javaLogin 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.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
packagecom.prgguru.jersey;importjavax.ws.rs.GET;importjavax.ws.rs.Path;importjavax.ws.rs.Produces;importjavax.ws.rs.QueryParam;importjavax.ws.rs.core.MediaType;//Path: http://localhost/<appln-folder-name>/login@Path("/login")publicclassLogin {// 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=xyzpublicString 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");}returnresponse;}/*** Method to check whether the entered credential is valid** @param uname* @param pwd* @return*/privatebooleancheckCredentials(String uname, String pwd){System.out.println("Inside checkCredentials");booleanresult =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;}returnresult;}} - Deploy the web application:Right click on the project ‘useraccount’ >> 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. |
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:
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:
[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.
You are always welcome to provide your comments and feedback from 24 Comments box.
[pgwriteforus]
[pgfeedback]
本文档详细介绍了如何使用Java和Jersey框架创建RESTful Web服务,包括配置MySQL数据库、实现用户注册与登录功能,并提供了测试REST API的方法。







5210

被折叠的 条评论
为什么被折叠?



