Beruflich Dokumente
Kultur Dokumente
RESTfulWebServicesQuickGuide
RESTfulWebServicesQuickGuide
Advertisements
PreviousPage
NextPage
RESTfulWebServicesIntroduction
WhatisRESTArchitecture?
REST stands for REpresentational State Transfer. REST is web standards based architecture and
uses HTTP Protocol. It revolves around resource where every component is a resource and a
resource is accessed by a common interface using HTTP standard methods. REST was first
introducedbyRoyFieldingin2000.
InRESTarchitecture,aRESTServersimplyprovidesaccesstoresourcesandRESTclientaccesses
andmodifiestheresources.HereeachresourceisidentifiedbyURIs/globalIDs.RESTusesvarious
representationstorepresentaresourceliketext,JSON,XML.JSONisthemostpopularone.
HTTPMethods
FollowingfiveHTTPmethodsarecommonlyusedinRESTbasedarchitecture.
GETProvidesareadonlyaccesstoaresource.
PUTUsedtocreateanewresource.
DELETEUsedtoremovearesource.
POSTUsedtoupdateaexistingresourceorcreateanewresource.
OPTIONSUsedtogetthesupportedoperationsonaresource.
IntroductiontoRESTFulWebServices
A web service is a collection of open protocols and standards used for exchanging data between
applications or systems. Software applications written in various programming languages and
runningonvariousplatformscanusewebservicestoexchangedataovercomputernetworkslike
the Internet in a manner similar to interprocess communication on a single computer. This
http://www.tutorialspoint.com/restful/restful_quick_guide.htm
1/29
11/16/2015
RESTfulWebServicesQuickGuide
interoperability (e.g., between Java and Python, or Windows and Linux applications) is due to the
useofopenstandards.
WebservicesbasedonRESTArchitectureareknownasRESTfulwebservices.Thesewebservices
use HTTP methods to implement the concept of REST architecture. A RESTful web service usually
definesaURI,UniformResourceIdentifieraservice,providesresourcerepresentationsuchasJSON
andsetofHTTPMethods.
CreatingRESTFulWebService
Innextchapters,we'llcreateawebservicesayusermanagementwithfollowingfunctionalities:
Sr.
HTTP
No.
Method
Operation
URI
Operation
GET
/UserService/users
Getlistofusers
ReadOnly
GET
/UserService/users/1 GetUserofId1
ReadOnly
PUT
/UserService/users/2 InsertUserwithId2
Idempotent
POST
/UserService/users/2 UpdateUserwithId2
N/A
DELETE
/UserService/users/1 DeleteUserwithId1
Idempotent
OPTIONS
/UserService/users
Listthesupportedoperationsinweb
service
Type
ReadOnly
RESTfulWebServicesEnvironmentSetup
Thistutorialwillguideyouonhowtoprepareadevelopmentenvironmenttostartyourworkwith
JerseyFrameworktocreateRESTfulWebServices.JerseyframeworkimplementsJAXRS2.0API
whichisstandardspecificationtocreateRESTfulwebservices.Thistutorialwillalsoteachyouhow
tosetupJDK,TomcatandEclipseonyourmachinebeforeyousetupJerseyFramework:
Step1SetupJavaDevelopmentKit(JDK):
YoucandownloadthelatestversionofSDKfromOracle'sJavasite:JavaSEDownloads
.Youwill
find instructions for installing JDK in downloaded files, follow the given instructions to install and
configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the
directory that contains java and javac, typically java_install_dir/bin and java_install_dir
respectively.
If you are running Windows and installed the JDK in C:\jdk1.7.0_75, you would have to put the
followinglineinyourC:\autoexec.batfile.
setPATH=C:\jdk1.7.0_75\bin;%PATH%
setJAVA_HOME=C:\jdk1.7.0_75
2/29
11/16/2015
RESTfulWebServicesQuickGuide
Properties,thenAdvanced,thenEnvironmentVariables.Then,youwouldupdatethePATHvalueand
presstheOKbutton.
On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.7.0_75 and you use the C
shell,youwouldputthefollowingintoyour.cshrcfile.
setenvPATH/usr/local/jdk1.7.0_75/bin:$PATH
setenvJAVA_HOME/usr/local/jdk1.7.0_75
Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder,
Eclipse,IntelliJIDEA,orSunONEStudio,compileandrunasimpleprogramtoconfirmthattheIDE
knowswhereyouinstalledJava,otherwisedopropersetupasgivendocumentoftheIDE.
Step2SetupEclipseIDE
AlltheexamplesinthistutorialhavebeenwrittenusingEclipseIDE.SoIwouldsuggestyoushould
havelatestversionofEclipseinstalledonyourmachine.
To
install
Eclipse
IDE,
http://www.eclipse.org/downloads/
download
the
latest
Eclipse
binaries
from
distributionintoaconvenientlocation.ForexampleinC:\eclipseonwindows,or/usr/local/eclipse
onLinux/UnixandfinallysetPATHvariableappropriately.
Eclipse can be started by executing the following commands on windows machine, or you can
simplydoubleclickoneclipse.exe
%C:\eclipse\eclipse.exe
EclipsecanbestartedbyexecutingthefollowingcommandsonUnix(Solaris,Linux,etc.)machine:
$/usr/local/eclipse/eclipse
Afterasuccessfulstartup,ifeverythingisfinethenitshoulddisplayfollowingresult:
http://www.tutorialspoint.com/restful/restful_quick_guide.htm
3/29
11/16/2015
RESTfulWebServicesQuickGuide
Step4SetupJerseyFrameworkLibraries
Nowifeverythingisfine,thenyoucanproceedtosetupyourJerseyframework.Followingarethe
simplestepstodownloadandinstalltheframeworkonyourmachine.
MakeachoicewhetheryouwanttoinstallJerseyonWindows,orUnixandthenproceedto
thenextsteptodownload.zipfileforwindowsand.tzfileforUnix.
Download
the
latest
version
https://jersey.java.net/download.html
of
Jersey
framework
binaries
from
Atthetimeofwritingthistutorial,Idownloadedjaxrsri2.17.ziponmyWindowsmachine
andwhenyouunzipthedownloadedfileitwillgiveyoudirectorystructureinsideE:\jaxrsri
2.17\jaxrsriasfollows.
You will find all the Jersey libraries in the directories C:\jaxrsri2.17\jaxrsri\lib and
dependencies in C:\jaxrsri2.17\jaxrsri\ext. Make sure you set your CLASSPATH variable on
this directory properly otherwise you will face problem while running your application. If you are
usingEclipsethenitisnotrequiredtosetCLASSPATHbecauseallthesettingwillbedonethrough
Eclipse.
Step5:SetupApacheTomcat:
http://www.tutorialspoint.com/restful/restful_quick_guide.htm
4/29
11/16/2015
RESTfulWebServicesQuickGuide
. Once you
downloadedtheinstallation,unpackthebinarydistributionintoaconvenientlocation.Forexample
inC:\apachetomcat7.0.59onwindows,or/usr/local/apachetomcat7.0.59onLinux/Unixandset
CATALINA_HOMEenvironmentvariablepointingtotheinstallationlocations.
Tomcat can be started by executing the following commands on windows machine, or you can
simplydoubleclickonstartup.bat
%CATALINA_HOME%\bin\startup.bat
or
C:\apachetomcat7.0.59\bin\startup.bat
TomcatcanbestartedbyexecutingthefollowingcommandsonUnix(Solaris,Linux,etc.)machine:
$CATALINA_HOME/bin/startup.sh
or
/usr/local/apachetomcat7.0.59/bin/startup.sh
After a successful startup, the default web applications included with Tomcat will be available by
visitinghttp://localhost:8080/.Ifeverythingisfinethenitshoulddisplayfollowingresult:
Further information about configuring and running Tomcat can be found in the documentation
includedhere,aswellasontheTomcatwebsite:http://tomcat.apache.org
Tomcatcanbestoppedbyexecutingthefollowingcommandsonwindowsmachine:
%CATALINA_HOME%\bin\shutdown
or
C:\apachetomcat7.0.59\bin\shutdown
Tomcat can be stopped by executing the following commands on Unix (Solaris, Linux, etc.)
machine:
$CATALINA_HOME/bin/shutdown.sh
http://www.tutorialspoint.com/restful/restful_quick_guide.htm
5/29
11/16/2015
RESTfulWebServicesQuickGuide
or
/usr/local/apachetomcat7.0.59/bin/shutdown.sh
Onceyouaredonewiththislaststep,youarereadytoproceedforyourfirstJerseyExamplewhich
youwillseeinthenextchapter.
RESTfulWebServicesFirstApplication
Let us start writing actual RESTful web services with Jersey Framework. Before you start writing
yourfirstexampleusingJerseyframework,youhavetomakesurethatyouhavesetupyourJersey
environmentproperlyasexplainedinRESTfulWebServicesEnvironmentSetup
tutorial.Ialso
assumethatyouhavealittlebitworkingknowledgewithEclipseIDE.
SoletusproceedtowriteasimpleJerseyApplicationwhichwillexposeawebservicemethodto
displaylistofusers.
Step1CreateJavaProject:
ThefirststepistocreateaDynamicWebProjectusingEclipseIDE.FollowtheoptionFile>New
>ProjectandfinallyselectDynamicWebProjectwizardfromthewizardlist.Nownameyour
projectasUserManagementusingthewizardwindowasfollows:
http://www.tutorialspoint.com/restful/restful_quick_guide.htm
6/29
11/16/2015
RESTfulWebServicesQuickGuide
Onceyourprojectiscreatedsuccessfully,youwillhavefollowingcontentinyourProjectExplorer:
http://www.tutorialspoint.com/restful/restful_quick_guide.htm
7/29
11/16/2015
RESTfulWebServicesQuickGuide
Step2AddRequiredLibraries:
AsasecondstepletusaddJerseyFrameworkanditsdependencies(libraries)inourproject.Copy
all jars from following directories of download jersey zip folder in WEBINF/lib directory of the
project.
\jaxrsri2.17\jaxrsri\api
\jaxrsri2.17\jaxrsri\ext
\jaxrsri2.17\jaxrsri\lib
Now, right click on your project name UserManagement and then follow the following option
available in context menu: Build Path > Configure Build Path to display the Java Build Path
window.
NowuseAdd JARs button available under Libraries tab to add the JARs present in WEBINF/lib
directory.
http://www.tutorialspoint.com/restful/restful_quick_guide.htm
8/29
11/16/2015
RESTfulWebServicesQuickGuide
Step3CreateSourceFiles:
NowletuscreateactualsourcefilesundertheUserManagementproject.Firstweneedtocreate
apackagecalledcom.tutorialspoint.Todothis,rightclickonsrcinpackageexplorersectionand
followtheoption:New>Package.
NextwewillcreateUserService.java,User.java,UserDao.javafilesunderthecom.tutorialspoint
package.
User.java
packagecom.tutorialspoint;
importjava.io.Serializable;
importjavax.xml.bind.annotation.XmlElement;
importjavax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="user")
publicclassUserimplementsSerializable{
privatestaticfinallongserialVersionUID=1L;
privateintid;
privateStringname;
privateStringprofession;
publicUser(){}
publicUser(intid,Stringname,Stringprofession){
this.id=id;
this.name=name;
this.profession=profession;
}
publicintgetId(){
returnid;
}
@XmlElement
publicvoidsetId(intid){
this.id=id;
}
publicStringgetName(){
returnname;
}
@XmlElement
publicvoidsetName(Stringname){
this.name=name;
}
publicStringgetProfession(){
returnprofession;
}
@XmlElement
publicvoidsetProfession(Stringprofession){
this.profession=profession;
}
UserDao.java
packagecom.tutorialspoint;
http://www.tutorialspoint.com/restful/restful_quick_guide.htm
9/29
11/16/2015
RESTfulWebServicesQuickGuide
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.ObjectInputStream;
importjava.io.ObjectOutputStream;
importjava.util.ArrayList;
importjava.util.List;
publicclassUserDao{
publicList<User>getAllUsers(){
List<User>userList=null;
try{
Filefile=newFile("Users.dat");
if(!file.exists()){
Useruser=newUser(1,"Mahesh","Teacher");
userList=newArrayList<User>();
userList.add(user);
saveUserList(userList);
}
else{
FileInputStreamfis=newFileInputStream(file);
ObjectInputStreamois=newObjectInputStream(fis);
userList=(List<User>)ois.readObject();
ois.close();
}
}catch(IOExceptione){
e.printStackTrace();
}catch(ClassNotFoundExceptione){
e.printStackTrace();
}
returnuserList;
}
}
UserService.java
packagecom.tutorialspoint;
importjava.util.List;
importjavax.ws.rs.GET;
importjavax.ws.rs.Path;
importjavax.ws.rs.Produces;
importjavax.ws.rs.core.MediaType;
@Path("/UserService")
publicclassUserService{
UserDaouserDao=newUserDao();
@GET
@Path("/users")
@Produces(MediaType.APPLICATION_XML)
publicList<User>getUsers(){
returnuserDao.getAllUsers();
}
}
Therearefollowingtwoimportantpointstonoteaboutthemainprogram,UserService.java:
1. Firststepistospecifyapathforthewebserviceusing@PathannotationtoUserService.
http://www.tutorialspoint.com/restful/restful_quick_guide.htm
10/29
11/16/2015
RESTfulWebServicesQuickGuide
2. Secondstepistospecifyapathfortheparticularwebservicemethodusing@Pathannotation
tomethodofUserService.
Step4CreateWeb.xmlconfigurationFile:
YouneedtocreateaWebxmlConfigurationfilewhichisanXMLfileandisusedtospecifyJersey
frameworkservletforourapplication.
web.xml
<?xmlversion="1.0"encoding="UTF8"?>
<webappxmlns:xsi="http://www.w3.org/2001/XMLSchemainstance"xmlns="http://java.sun.com/xml/ns/javaee"xsi:schemaLocation
<displayname>UserManagement</displayname>
<servlet>
<servletname>JerseyRESTfulApplication</servletname>
<servletclass>org.glassfish.jersey.servlet.ServletContainer</servletclass>
<initparam>
<paramname>jersey.config.server.provider.packages</paramname>
<paramvalue>com.tutorialspoint</paramvalue>
</initparam>
</servlet>
<servletmapping>
<servletname>JerseyRESTfulApplication</servletname>
<urlpattern>/rest/*</urlpattern>
</servletmapping>
</webapp>
Step5DeployingtheProgram
Once you are done with creating source and web configuration files, you are ready for this step
whichiscompilingandrunningyourprogram.Todothis,usingEclipse,exportyourapplicationasa
warfileanddeploythesameintomcat.TocreateWARfileusingeclipse,followtheoptionFile>
export>Web>WarFileandfinallyselectprojectUserManagementanddestinationfolder.To
deploy war file in Tomcat, place the UserManagement.war in Tomcat Installation Directory >
webappsdirectoryandstarttheTomcat.
Step6RunningtheProgram
WeareusingPostman
Make
request
,aChromeextension,totestourwebservices.
to
UserManagement
to
get
list
of
all
the
users.
Put
http://localhost:8080/UserManagement/rest/UserService/usersinPOSTMANwithGETrequestand
seethebelowresult.
http://www.tutorialspoint.com/restful/restful_quick_guide.htm
11/29
11/16/2015
RESTfulWebServicesQuickGuide
Congratulations, you have created your first Spring Application successfully. You can see the
flexibilityofaboveSpringapplicationbychangingthevalueof"message"propertyandkeepingboth
the source files unchanged. Further, let us start doing something more interesting in next few
chapters.
RESTfulWebServicesResources
WhatisaResource?
In REST architecture, everything is a resource. These resources can be text files, html pages,
images, videos or dynamic business data. REST Server simply provides access to resources and
REST client accesses and modifies the resources. Here each resource is identified by URIs/ global
IDs.RESTusesvariousrepresentationstorepresentaresourceliketext,JSON,XML.XMLandJSON
arethemostpopularrepresentationsofresources.
RepresentationofResources
A resource in REST is similar Object in Object Oriented Programming or similar to Entity in a
Database. Once a resource is identified then its representation is to be decided using a standard
format so that server can send the resource in above said format and client can understand the
sameformat.
For example, in RESTful Web Services First Application
representedusingfollowingXMLformat:
<user>
<id>1</id>
<name>Mahesh</name>
<profession>Teacher</profession>
</user>
SameresourcecanberepresentedinJSONformat:
{
"id":1,
"name":"Mahesh",
http://www.tutorialspoint.com/restful/restful_quick_guide.htm
12/29
11/16/2015
RESTfulWebServicesQuickGuide
"profession":"Teacher"
}
CharacteristicsofaGoodRepresentation
InREST,thereisnorestrictionontheformatofaresourcerepresentation.AclientcanaskforJSON
representation where as another client may ask for XML representation of same resource to the
serverandsoon.ItisresponsibilityoftheRESTservertopasstheclienttheresourceintheformat
that client understands. Following are important points to be considered while designing a
representationformatofaresourceinaRESTfulwebservices.
Understandability: Both Server and Client should be able to understand and utilize the
representationformatoftheresource.
Completeness:Formatshouldbeabletorepresentaresourcecompletely.Forexample,a
resourcecancontainanotherresource.Formatshouldbeabletorepresentsimpleaswellas
complexstructuresofresources.
Linkablity:Aresourcecanhavealinkagetoanotherresource,aformatshouldbeableto
handlessuchsituations.
RESTfulWebServicesMessages
RESTfulwebservicesmakeuseofHTTPprotocolasamediumofcommunicationbetweenclientand
server.AclientsendsamessageinformofaHTTPRequestandserverrespondsinformofaHTTP
Response. This technique is terms as Messaging. These messages contain message data and
metadata that is information about message itself. Let's have a look on HTTP Request and HTTP
ResponsemessagesforHTTP1.1.
HTTPRequest
AHTTPRequesthasfivemajorparts:
VerbIndicateHTTPmethodssuchasGET,POSTetc.
URIContainstheURI,UniformResourceIdentifiertoidentifytheresourceonserver
HTTPVersionIndicateHTTPversion,forexampleHTTPv1.1.
http://www.tutorialspoint.com/restful/restful_quick_guide.htm
13/29
11/16/2015
RESTfulWebServicesQuickGuide
Request Header Contains metadata for the HTTP Request message as keyvalue pairs.
Forexample,client(orbrowser)type,formatsupportedbyclient,formatofmessagebody,
cachesettingsetc.
RequestBodyMessagecontentorResourcerepresentation.
HTTPResponse
AHTTPResponsehasfourmajorparts:
Status/ResponseCodeIndicateServerstatusfortherequestedresource.Forexample
404meansresourcenotfoundand200meansresponseisok.
HTTPVersionIndicateHTTPversion,forexampleHTTPv1.1.
Response Header Contains metadata for the HTTP Response message as keyvalue
pairs.Forexample,contentlength,contenttype,responsedate,servertypeetc.
ResponseBodyResponsemessagecontentorResourcerepresentation.
Example
Puthttp://localhost:8080/UserManagement/rest/UserService/usersinPOSTMANwithGETrequest.
IfyouclickonPreviewbuttonresidingnearsendbuttonofPostmanandthenclickonSendbutton,
youmayseethefollowingoutput.
http://www.tutorialspoint.com/restful/restful_quick_guide.htm
14/29
11/16/2015
RESTfulWebServicesQuickGuide
Hereyoucansee,thebrowsersentaGETrequestandreceivedaresponsebodyasXML.
RESTfulWebServicesAddressing
Addressingreferstolocatingaresourceormultipleresourceslyingontheserver.Itisanalogousto
locateapostaladdressofaperson.
EachresourceinRESTarchitectureisidentifiedbyitsURI,UniformResourceIdentifier.AURIisof
followingformat:
<protocol>://<servicename>/<ResourceType>/<ResourceID>
Purpose of an URI is to locate a resource(s) on the server hosting the web service. Another
important attribute of a request is VERB which identifies the operation to be performed on the
resource. For example, in RESTful Web Services First Application
tutorial, URI is
http://localhost:8080/UserManagement/rest/UserService/usersandVERBisGET.
ConstructingastandardURI
FollowingareimportantpointstobeconsideredwhiledesigningaURI:
UsePluralNounUsepluralnountodefineresources.Forexample,we'veusedusersto
identifyusersasaresource.
AvoidusingspacesUseunderscore(_)orhyphen()whenusingalongresourcename,
forexample,useauthorized_usersinsteadofauthorized%20users.
UselowercaselettersAlthoughURIiscaseinsensitive,itisgoodpracticetokeepurlin
lowercaselettersonly.
MaintainBackwardCompatibilityAsWebServiceisapublicservice,aURIoncemade
publicshouldalwaysbeavailable.Incase,URIgetsupdated,redirecttheolderURItonew
URIusingHTTPStatuscode,300.
http://www.tutorialspoint.com/restful/restful_quick_guide.htm
15/29
11/16/2015
RESTfulWebServicesQuickGuide
UseHTTPVerbAlwaysuseHTTPVerblikeGET,PUT,andDELETEtodotheoperationson
theresource.ItisnotgoodtouseoperationsnamesinURI.Forexample,followingisapoor
URItofetchauser.
http://localhost:8080/UserManagement/rest/UserService/getUser/1
FollowingisanexampleofgoodURItofetchauser.
http://localhost:8080/UserManagement/rest/UserService/users/1
LetServerdecidetheoperationbasedonHTTPverb.
RESTfulWebServicesMethods
As we have discussed so far that RESTful web service makes heavy uses of HTTP verbs to
determine the operation to be carried out on the specified resource(s). Following table states the
examplesofcommonuseofHTTPVerbs.
Sr.
HTTP
No. Method
URI
GET
http://localhost:8080/UserManagement/rest/UserService/users
GET
http://localhost:8080/UserManagement/rest/UserService/users/1
PUT
http://localhost:8080/UserManagement/rest/UserService/users/2
Operation
Getlistof
users
GetUser
ofId1
InsertUser
withId2
Operation
Type
ReadOnly
ReadOnly
Idempotent
Update
4
POST
http://localhost:8080/UserManagement/rest/UserService/users/2 Userwith
N/A
Id2
Delete
5
DELETE
http://localhost:8080/UserManagement/rest/UserService/users/1 Userwith
Idempotent
Id1
Listthe
supported
6
OPTIONS http://localhost:8080/UserManagement/rest/UserService/users
operations
ReadOnly
inweb
service
Returns
7
HEAD
http://localhost:8080/UserManagement/rest/UserService/users
onlyHTTP
Header,no
ReadOnly
Body.
Hereareimportantpointstobeconsidered:
GEToperationsarereadonlyandaresafe.
http://www.tutorialspoint.com/restful/restful_quick_guide.htm
16/29
11/16/2015
RESTfulWebServicesQuickGuide
PUTandDELETEoperationsareidempotentmeanstheirresultwillalwayssamenomatter
howmanytimestheseoperationsareinvoked.
PUTandPOSToperationarenearlysamewiththedifferencelyingonlyintheresultwhere
PUToperationisidempotentandPOSToperationcancausedifferentresult.
Example
Let'supdateExamplecreatedinRESTfulWebServicesFirstApplication
tutorialtocreateaWeb
service which can perform CRUD (Create, Read, Update, Delete) operations. For simplicity, we've
usedafileI/OtoreplaceDatabaseoperations.
UpdateUserService.java,User.java,UserDao.javafilesunderthecom.tutorialspointpackage.
User.java
packagecom.tutorialspoint;
importjava.io.Serializable;
importjavax.xml.bind.annotation.XmlElement;
importjavax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="user")
publicclassUserimplementsSerializable{
privatestaticfinallongserialVersionUID=1L;
privateintid;
privateStringname;
privateStringprofession;
publicUser(){}
publicUser(intid,Stringname,Stringprofession){
this.id=id;
this.name=name;
this.profession=profession;
}
publicintgetId(){
returnid;
}
@XmlElement
publicvoidsetId(intid){
this.id=id;
}
publicStringgetName(){
returnname;
}
@XmlElement
publicvoidsetName(Stringname){
this.name=name;
}
publicStringgetProfession(){
returnprofession;
}
@XmlElement
publicvoidsetProfession(Stringprofession){
this.profession=profession;
}
http://www.tutorialspoint.com/restful/restful_quick_guide.htm
17/29
11/16/2015
RESTfulWebServicesQuickGuide
@Override
publicbooleanequals(Objectobject){
if(object==null){
returnfalse;
}elseif(!(objectinstanceofUser)){
returnfalse;
}else{
Useruser=(User)object;
if(id==user.getId()
&&name.equals(user.getName())
&&profession.equals(user.getProfession())
){
returntrue;
}
}
returnfalse;
}
}
UserDao.java
packagecom.tutorialspoint;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.ObjectInputStream;
importjava.io.ObjectOutputStream;
importjava.util.ArrayList;
importjava.util.List;
publicclassUserDao{
publicList<User>getAllUsers(){
List<User>userList=null;
try{
Filefile=newFile("Users.dat");
if(!file.exists()){
Useruser=newUser(1,"Mahesh","Teacher");
userList=newArrayList<User>();
userList.add(user);
saveUserList(userList);
}
else{
FileInputStreamfis=newFileInputStream(file);
ObjectInputStreamois=newObjectInputStream(fis);
userList=(List<User>)ois.readObject();
ois.close();
}
}catch(IOExceptione){
e.printStackTrace();
}catch(ClassNotFoundExceptione){
e.printStackTrace();
}
returnuserList;
}
publicUsergetUser(intid){
List<User>users=getAllUsers();
for(Useruser:users){
if(user.getId()==id){
returnuser;
}
http://www.tutorialspoint.com/restful/restful_quick_guide.htm
18/29
11/16/2015
RESTfulWebServicesQuickGuide
}
returnnull;
}
publicintaddUser(UserpUser){
List<User>userList=getAllUsers();
booleanuserExists=false;
for(Useruser:userList){
if(user.getId()==pUser.getId()){
userExists=true;
break;
}
}
if(!userExists){
userList.add(pUser);
saveUserList(userList);
return1;
}
return0;
}
publicintupdateUser(UserpUser){
List<User>userList=getAllUsers();
for(Useruser:userList){
if(user.getId()==pUser.getId()){
intindex=userList.indexOf(user);
userList.set(index,pUser);
saveUserList(userList);
return1;
}
}
return0;
}
publicintdeleteUser(intid){
List<User>userList=getAllUsers();
for(Useruser:userList){
if(user.getId()==id){
intindex=userList.indexOf(user);
userList.remove(index);
saveUserList(userList);
return1;
}
}
return0;
}
privatevoidsaveUserList(List<User>userList){
try{
Filefile=newFile("Users.dat");
FileOutputStreamfos;
fos=newFileOutputStream(file);
ObjectOutputStreamoos=newObjectOutputStream(fos);
oos.writeObject(userList);
oos.close();
}catch(FileNotFoundExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
}
http://www.tutorialspoint.com/restful/restful_quick_guide.htm
19/29
11/16/2015
RESTfulWebServicesQuickGuide
UserService.java
packagecom.tutorialspoint;
importjava.io.IOException;
importjava.util.List;
importjavax.servlet.http.HttpServletResponse;
importjavax.ws.rs.Consumes;
importjavax.ws.rs.DELETE;
importjavax.ws.rs.FormParam;
importjavax.ws.rs.GET;
importjavax.ws.rs.OPTIONS;
importjavax.ws.rs.POST;
importjavax.ws.rs.PUT;
importjavax.ws.rs.Path;
importjavax.ws.rs.PathParam;
importjavax.ws.rs.Produces;
importjavax.ws.rs.core.Context;
importjavax.ws.rs.core.MediaType;
@Path("/UserService")
publicclassUserService{
UserDaouserDao=newUserDao();
privatestaticfinalStringSUCCESS_RESULT="<result>success</result>";
privatestaticfinalStringFAILURE_RESULT="<result>failure</result>";
@GET
@Path("/users")
@Produces(MediaType.APPLICATION_XML)
publicList<User>getUsers(){
returnuserDao.getAllUsers();
}
@GET
@Path("/users/{userid}")
@Produces(MediaType.APPLICATION_XML)
publicUsergetUser(@PathParam("userid")intuserid){
returnuserDao.getUser(userid);
}
@PUT
@Path("/users")
@Produces(MediaType.APPLICATION_XML)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
publicStringcreateUser(@FormParam("id")intid,
@FormParam("name")Stringname,
@FormParam("profession")Stringprofession,
@ContextHttpServletResponseservletResponse)throwsIOException{
Useruser=newUser(id,name,profession);
intresult=userDao.addUser(user);
if(result==1){
returnSUCCESS_RESULT;
}
returnFAILURE_RESULT;
}
@POST
@Path("/users")
@Produces(MediaType.APPLICATION_XML)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
http://www.tutorialspoint.com/restful/restful_quick_guide.htm
20/29
11/16/2015
RESTfulWebServicesQuickGuide
publicStringupdateUser(@FormParam("id")intid,
@FormParam("name")Stringname,
@FormParam("profession")Stringprofession,
@ContextHttpServletResponseservletResponse)throwsIOException{
Useruser=newUser(id,name,profession);
intresult=userDao.updateUser(user);
if(result==1){
returnSUCCESS_RESULT;
}
returnFAILURE_RESULT;
}
@DELETE
@Path("/users/{userid}")
@Produces(MediaType.APPLICATION_XML)
publicStringdeleteUser(@PathParam("userid")intuserid){
intresult=userDao.deleteUser(userid);
if(result==1){
returnSUCCESS_RESULT;
}
returnFAILURE_RESULT;
}
@OPTIONS
@Path("/users")
@Produces(MediaType.APPLICATION_XML)
publicStringgetSupportedOperations(){
return"<operations>GET,PUT,POST,DELETE</operations>";
}
}
NowusingEclipse,exportyourapplicationasawarfileanddeploythesameintomcat.Tocreate
WAR file using eclipse, follow the option File > export > Web > War File and finally select
project UserManagement and destination folder. To deploy war file in Tomcat, place the
UserManagement.war in Tomcat Installation Directory > webapps directory and start the
Tomcat.
TestingtheWebService
JerseyprovidesAPIstocreateaWebServiceClienttotestwebservices.We'vecreatedasample
testclassWebServiceTester.javaunderthecom.tutorialspointpackageinthesameproject.
WebServiceTester.java
packagecom.tutorialspoint;
importjava.util.List;
importjavax.ws.rs.client.Client;
importjavax.ws.rs.client.ClientBuilder;
importjavax.ws.rs.client.Entity;
importjavax.ws.rs.core.Form;
importjavax.ws.rs.core.GenericType;
importjavax.ws.rs.core.MediaType;
publicclassWebServiceTester{
privateClientclient;
privateStringREST_SERVICE_URL="http://localhost:8080/UserManagement/rest/UserService/users";
privatestaticfinalStringSUCCESS_RESULT="<result>success</result>";
http://www.tutorialspoint.com/restful/restful_quick_guide.htm
21/29
11/16/2015
RESTfulWebServicesQuickGuide
privatestaticfinalStringPASS="pass";
privatestaticfinalStringFAIL="fail";
privatevoidinit(){
this.client=ClientBuilder.newClient();
}
publicstaticvoidmain(String[]args){
WebServiceTestertester=newWebServiceTester();
//initializethetester
tester.init();
//testgetallusersWebServiceMethod
tester.testGetAllUsers();
//testgetuserWebServiceMethod
tester.testGetUser();
//testupdateuserWebServiceMethod
tester.testUpdateUser();
//testadduserWebServiceMethod
tester.testAddUser();
//testdeleteuserWebServiceMethod
tester.testDeleteUser();
}
//Test:Getlistofallusers
//Test:Checkiflistisnotempty
privatevoidtestGetAllUsers(){
GenericType<List<User>>list=newGenericType<List<User>>(){};
List<User>users=client
.target(REST_SERVICE_URL)
.request(MediaType.APPLICATION_XML)
.get(list);
Stringresult=PASS;
if(users.isEmpty()){
result=FAIL;
}
System.out.println("Testcasename:testGetAllUsers,Result:"+result);
}
//Test:GetUserofid1
//Test:Checkifuserissameassampleuser
privatevoidtestGetUser(){
UsersampleUser=newUser();
sampleUser.setId(1);
Useruser=client
.target(REST_SERVICE_URL)
.path("/{userid}")
.resolveTemplate("userid",1)
.request(MediaType.APPLICATION_XML)
.get(User.class);
Stringresult=FAIL;
if(sampleUser!=null&&sampleUser.getId()==user.getId()){
result=PASS;
}
System.out.println("Testcasename:testGetUser,Result:"+result);
}
//Test:UpdateUserofid1
//Test:CheckifresultissuccessXML.
privatevoidtestUpdateUser(){
Formform=newForm();
form.param("id","1");
form.param("name","suresh");
form.param("profession","clerk");
StringcallResult=client
.target(REST_SERVICE_URL)
.request(MediaType.APPLICATION_XML)
http://www.tutorialspoint.com/restful/restful_quick_guide.htm
22/29
11/16/2015
RESTfulWebServicesQuickGuide
.post(Entity.entity(form,
MediaType.APPLICATION_FORM_URLENCODED_TYPE),
String.class);
Stringresult=PASS;
if(!SUCCESS_RESULT.equals(callResult)){
result=FAIL;
}
System.out.println("Testcasename:testUpdateUser,Result:"+result);
}
//Test:AddUserofid2
//Test:CheckifresultissuccessXML.
privatevoidtestAddUser(){
Formform=newForm();
form.param("id","2");
form.param("name","naresh");
form.param("profession","clerk");
StringcallResult=client
.target(REST_SERVICE_URL)
.request(MediaType.APPLICATION_XML)
.put(Entity.entity(form,
MediaType.APPLICATION_FORM_URLENCODED_TYPE),
String.class);
Stringresult=PASS;
if(!SUCCESS_RESULT.equals(callResult)){
result=FAIL;
}
System.out.println("Testcasename:testAddUser,Result:"+result);
}
//Test:DeleteUserofid2
//Test:CheckifresultissuccessXML.
privatevoidtestDeleteUser(){
StringcallResult=client
.target(REST_SERVICE_URL)
.path("/{userid}")
.resolveTemplate("userid",2)
.request(MediaType.APPLICATION_XML)
.delete(String.class);
Stringresult=PASS;
if(!SUCCESS_RESULT.equals(callResult)){
result=FAIL;
}
System.out.println("Testcasename:testDeleteUser,Result:"+result);
}
}
Now run the tester using Eclipse. Right click on the file, and follow the option Run as > Java
Application.You'llseethefollowingresultinEclipseconsole:
Testcasename:testGetAllUsers,Result:pass
Testcasename:testGetUser,Result:pass
Testcasename:testUpdateUser,Result:pass
Testcasename:testAddUser,Result:pass
Testcasename:testDeleteUser,Result:pass
RESTfulWebServicesStatelessness
http://www.tutorialspoint.com/restful/restful_quick_guide.htm
23/29
11/16/2015
RESTfulWebServicesQuickGuide
As per REST architecture, a RESTful web service should not keep a client state on server. This
restrictioniscalledstatelessness.Itisresponsibilityoftheclienttopassitscontexttoserverand
then server can store this context to process client's further request. For example, session
maintainedbyserverisidentifiedbysessionidentifierpassedbytheclient.
RESTful Web services should adhere to this restriction. We've seen in RESTful Web Services
Methods
tutorial,thatWebservicemethodsarenotstoringanyinformationfromtheclientthey
areinvokedfrom.
ConsiderthefollowingURL:
http://localhost:8080/UserManagement/rest/UserService/users/1
Ifyouhittheaboveurlusingbrowser,usingjavabasedclientorusingpostman,resultwillalways
betheUserXMLwhoseIdis1becauseserverisnotstoredanyinformationabouttheclient.
<user>
<id>1</id>
<name>mahesh</name>
<profession>1</profession>
</user>
AdvantagesofStatelessness
FollowingarethebenefitsofstatelessnessinRESTfulwebservices
Webservicescantreateachmethodrequestindependently.
Web services need not to maintain client's previous interactions. It simplifies application
design.
AsHTTPisitselfastatelessnessprotocol,RESTfulWebservicesworkseamlesslywithHTTP
protocol.
DisadvantagesofStatelessness
FollowingarethedisadvantagesofstatelessnessinRESTfulwebservices
Web services need to get extra information in each request and then interpret to get the
client'sstateincaseclientinteractionsaretobetakencareof.
RESTfulWebServicesCaching
Cachingreferstostoringserverresponseinclientitselfsothataclientneedsnottomakeserver
requestforsameresourceagainandagain.Aserverresponseshouldhaveinformationabouthowa
caching is to be done so that a client caches response for a period of time or never caches the
serverresponse.
Followingaretheheaderswhichaserverresponsecanhaveinordertoconfigureaclient'scaching:
http://www.tutorialspoint.com/restful/restful_quick_guide.htm
24/29
11/16/2015
RESTfulWebServicesQuickGuide
Sr.No.
Header
Description
Date
DateandTimeoftheresourcewhenitwascreated.
LastModified
DateandTimeoftheresourcewhenitwaslastmodified.
CacheControl
Primaryheadertocontrolcaching.
Expires
Expirationdateandtimeofcaching
Age
Durationinsecondsfromwhenresourcewasfetchedfromtheserver.
CacheControlHeader
FollowingarethedetailsofCacheControlheader
Sr.
Directive
Description
Public
Indicatesthatresourceiscacheablebyanycomponent.
Private
No.
nocache/no
store
maxage
must
revalidate
Indicatesthatresourceiscacheablebyonlyclientandserver,nointermediary
cancachetheresource.
Indicatesthatresourceisnotcacheable
Indicatesthecachingisvaliduptomaxageinseconds.Afterthis,clienthasto
makeanotherrequest.
Indicationtoservertorevalidateresourceifmaxagehaspassed.
BestPractices
Alwayskeepstaticcontentslikeimages,css,JavaScriptcacheable,withexpirationdateof2
to3days.
Neverkeepexpirydatetoohigh.
Dynamiccontentsshouldbecachedforfewhoursonly.
http://www.tutorialspoint.com/restful/restful_quick_guide.htm
25/29
11/16/2015
RESTfulWebServicesQuickGuide
RESTfulWebServicesSecurity
AsRESTfulwebservicesworkwithHTTPURLsPathssoitisveryimportanttosafeguardaRESTful
webserviceinthesamemannerasawebsiteisbesecured.Followingarethebestpracticestobe
followedwhiledesigningaRESTfulwebservice.
Validation Validate all inputs on the server. Protect your server against SQL or NoSQL
injectionattacks.
SessionbasedauthenticationUsesessionbasedauthenticationtoauthenticateauser
wheneverarequestismadetoaWebServicemethod.
No sensitive data in URL Never use username, password or session token in URL ,
thesevaluesshouldbepassedtoWebServiceviaPOSTmethod.
Restriction on Method execution Allow restricted use of methods like GET, POST,
DELETE.GETmethodshouldnotbeabletodeletedata.
Validate Malformed XML/JSON Check for well formed input passed to a web service
method.
ThrowgenericErrorMessagesAwebservicemethodshoulduseHTTPerrormessages
like403toshowaccessforbiddenetc.
HTTPStatusCodes
Always use standard HTTP codes while returning HTTP response to the client. Following are the
statuscodes.
http://www.tutorialspoint.com/restful/restful_quick_guide.htm
26/29
11/16/2015
Sr.
RESTfulWebServicesQuickGuide
HTTP
No. Code
Description
200
OK,showssuccess.
201
204
304
400
BADREQUEST,statesthatinvalidinputisprovidede.g.validationerror,missingdata.
401
UNAUTHORIZED,statesthatuserisusinginvalidorwrongauthenticationtoken.
403
404
409
10
500
CREATED,whenaresourceissuccessfulcreatedusingPOSTorPUTrequest.Returnlinkto
newlycreatedresourceusinglocationheader.
NOCONTENT,whenresponsebodyisemptyforexample,aDELETErequest.
NOTMODIFIED,usedtoreducenetworkbandwidthusageincaseofconditionalGET
requests.Responsebodyshouldbeempty.Headersshouldhavedate,locationetc.
FORBIDDEN,statesthatuserisnothavingaccesstomethodbeingusedforexample,
deleteaccesswithoutadminrights.
NOTFOUND,statesthatmethodisnotavailable.
CONFLICT,statesconflictsituationwhileexecutingthemethodforexample,adding
duplicateentry.
INTERNALSERVERERROR,statesthatserverhasthrownsomeexceptionwhile
executingthemethod.
RESTfulWebServicesJava(JAXRS)
JAXRS stands for JAVA API for RESTful Web Services. JAXRS is a JAVA based programming
languageAPIandspecificationtoprovidesupportforcreatedRESTfulWebservices.Its2.0version
wasreleasedin24May2013.JAXRSmakesheavyuseofannotationsavailablefromJavaSE5to
simplify development of JAVA based web services creation and deployment. It also provides
supportsforcreatingclientsforRESTfulwebservices.
Specification
Followingarethecommonlyusedannotationstomaparesourceasawebserviceresource.
Sr.
Annotation
Description
@Path
Relativepathoftheresourceclass/method.
@GET
HTTPGetrequest,usedtofetchresource.
@PUT
HTTPPUTrequest,usedtocreateresource.
@POST
HTTPPOSTrequest,usedtocreate/updateresource.
@DELETE
HTTPDELETErequest,usedtodeleteresource.
@HEAD
HTTPHEADrequest,usedtogetstatusofmethodavailability.
@Produces
StatestheHTTPResponsegeneratedbywebservice,forexample
No.
http://www.tutorialspoint.com/restful/restful_quick_guide.htm
27/29
11/16/2015
RESTfulWebServicesQuickGuide
APPLICATION/XML,TEXT/HTML,APPLICATION/JSONetc.
StatestheHTTPRequesttype,forexampleapplication/xwwwformurlencoded
@Consumes
@PathParam
Bindstheparameterpassedtomethodtoavalueinpath.
10
@QueryParam
Bindstheparameterpassedtomethodtoaqueryparameterinpath.
11
@MatrixParam
BindstheparameterpassedtomethodtoaHTTPmatrixparameterinpath.
12
@HeaderParam BindstheparameterpassedtomethodtoaHTTPheader.
13
@CookieParam
BindstheparameterpassedtomethodtoaCookie.
14
@FormParam
Bindstheparameterpassedtomethodtoaformvalue.
15
@DefaultValue
Assignsadefaultvaluetoaparameterpassedtomethod.
16
@Context
ContextoftheresourceforexampleHTTPRequestasacontext.
toacceptformdatainHTTPbodyduringPOSTrequest.
We'veusedJersey,areferenceimplementationofJAXRS2.0byOracle,inRESTfulWebServices
FirstApplication
andRESTfulWebServicesMethods
PreviousPage
tutorialpages.
NextPage
Advertisements
http://www.tutorialspoint.com/restful/restful_quick_guide.htm
28/29
11/16/2015
RESTfulWebServicesQuickGuide
Write for us
FAQ's
Helping
Contact
http://www.tutorialspoint.com/restful/restful_quick_guide.htm
go
29/29