Step : 1
Create a java class. As i have created a sample class named "Student".
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
//import javax.xml.bind.annotation.XmlRootElement;
@Path("/student")
public class Student {
@GET
@Path("/name")
@Produces(MediaType.APPLICATION_XML)
public String getStudentName()
{
return "My name is santanu";
}
@GET
@Path("/contact/{contact}")
@Produces(MediaType.TEXT_PLAIN)
public String getContact(@PathParam("contact") String contact)
{
return "My contact no is :" + contact;
}
}
Step : 2
Create a dispatcher servlet with the filename "web.xml" , where you will call jersey api packages and your created package name
where your class reside.here is my servlet xml file.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<servlet>
<servlet-name>student</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.pck.classes</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>student</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
Step : 3
Hurray !! your job is done.
Now your job is to call the servlet class with the name given in @Path annotation.
Note: If you mention @Path annotation just above your method also then you should give that path name also in the URL.
In my case i called my servlet class like this.
http://localhost:8080/restapi/student/name : this one is for first method which produces XML o/p
http://localhost:8080/restapi/student/contact/88483697493 : this one is for second method which produces text o/p.
Note : @Pathparam annotation is used to get the parameter value passes through the URL.