Before we proceed, we need almost four things up and running as part of our dev environment. Here I will be using following resources in order to design the simple RESTful service.
In nearly 4 steps we can configure and build the complete RESTful API.
Add below code snippet inside your pom.xml file. This will add the jersey-server library into the project.
web.xml
Add the below code snippet in your web.xml file.
Java Class:
Add the below java code into your java file.
That's pretty much it guys, now you may go ahead and run the server and run the below url
http://localhost:8080/MyProject/restful/hello/greeting
OR
http://localhost:8080/MyProject/restful/hello/restFulWorld
- Eclipse
- Tomcat
- Jersey library
- Maven
In nearly 4 steps we can configure and build the complete RESTful API.
- Open up your Eclipse IDE and create a dynamic web project and then convert it into the Maven project.
- Add the jersey-server dependency.
- Configure the jersey-server class and package entry into the web.xml file.
- Create the java class which will configure the url and request type and also will prepare the response.
Add below code snippet inside your pom.xml file. This will add the jersey-server library into the project.
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.8</version>
</dependency>
web.xml
Add the below code snippet in your web.xml file.
<servlet>
<servlet-name>my-jersey</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.services.rest</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>my-jersey</servlet-name>
<url-pattern>/restful/*</url-pattern>
</servlet-mapping>
Java Class:
Add the below java code into your java file.
package com.services.rest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
@Path("/hello")
public class FirstRestService {
@GET
@Path("/{param}")
public Response sendMsg(@PathParam("param") String msg){
String output = "<h1>Hello! this is a : </h1>" + "<p>"+msg+"</p>";
return Response.status(200).entity(output).build();
}
@GET
@Path("/greeting")
public String response(){
return "<h1>Hello World</h1>";
}
}
That's pretty much it guys, now you may go ahead and run the server and run the below url
http://localhost:8080/MyProject/restful/hello/greeting
OR
http://localhost:8080/MyProject/restful/hello/restFulWorld
Thank you.
ReplyDeleteNice article.thanks for sharing good post . this is good resource for jersey tutorials
ReplyDeletejersey tutorials