In this tutorial, we will create a restful web service that attach a client request to a specific resource. We use an example in which resource is information about users (id and name). If the server receives a request as:
package my.third.rest; public class User { private String id; private String name; public User(String id, String name){ this.id = id; this.name = name; } public void setName(String name){ this.name = name; } public String getID(){ return this.id; } public String getName(){ return this.name; } }
package my.third.rest; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; 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; @Path("users") //attach client request to resource: .../users public class RestResource { Map<String,User> listUsers; //initialize some resources public RestResource(){ listUsers = new HashMap<String,User>(); listUsers.put("1",new User("1", "John")); listUsers.put("2",new User("2", "Peter")); } //return list of users @GET @Produces(MediaType.TEXT_PLAIN) public String listOfUsersInText(){ String list=""; for (Entry<String,User> u:listUsers.entrySet()){ list += u.getValue().getName() + "\n"; } return list; } //return user information corresponding to the requested uid. @GET @Path("{uid}") //attach client request to resource: .../users/<uid> @Produces(MediaType.TEXT_PLAIN) public String getUID(@PathParam("uid") String uid){ //@PathParam is used to inject values from the URL into a method parameter // in this way you inject the id of the user into the method to get the correct user if (!listUsers.containsKey(uid)) return "User not exist!"; return listUsers.get(uid).getID()+":"+listUsers.get(uid).getName(); } }
<?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" 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_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>rest</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>my.first.rest;my.third.rest</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>Jersey REST Service</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> </web-app>