Monday, December 3, 2018

Write Your First REST Webservice

I recently learned writing REST based webservice with the help of tutorialspoint.com.
With this blog i intend to write down my learning in an oversimplified form so that it can come handy for anyone who is a naive.

Steps:
1. Create a new Dynamic Web project (in Eclipse goto file -- > New --> Project -- >Web -- > DynamicWeb project)

for this example i intend to deploy it in weblogic which is why selected the mentioned configuration. you may change it as per your requirement.

2. For this example, i intend to create a static list of player and save it in .dat file and i shall be able to access the same through its id or shall be able to access all the players.
Required jar files can be found in attached source code's lib folder
lets jump on coding part:

create 3 java class(detailed code can be found in the attached application, i am putting screenshot to better understand the code):
Player.java : pojo class to contain the player info


PlayerDao.java : to perform the save and retrieve function

PlayerService.java : This class has the methods which will be accessible through REST calls

Here @Path determines the url which would be used to access the webservice
web.xml shall be automatically generated for you, for this example add following entries:

Please note that i have specified the url to start as rest in this case

3. Right click on the project in eclipse and select export --> war File and select a location where the war would be created.

4. deploy this war in weblogic .
The Webservice can be access at :

To get all the players:
http://localhost:<port>/TestRestWSWeblogic/rest/PlayerService/player


to get player by id
http://localhost:<port>/TestRestWSWeblogic/rest/PlayerService/player/2


Here:
TestRestWSWeblogic : is the contect of the application
rest: defined in web.xml in url-pattern tag
PlayerService : @path defined for PlayerService.java class
player: @Path defined for getTrackInJSON method
player/2 :  @Path("/player/{playerid}") defined in getUser method


Sourcecode can be downloaded from here.

Please feel free to post your questions on the same.
In next few blogs, i would be sharing basic hibernate tutorial and its integration with REST Webservice application where it would use more HTTP methods like put/delete

No comments:

Post a Comment