See the presentation describing REST.
The example may be downloaded here: jersey-sample.zip
Check the sample, see how it works. The application is inspired by the sample REST application. The application provides two resources - a message resource and a person resource. The application supports just GET method for both resources, therefore you are able to get person and message resources.
The following are the dependencies we are using:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${version.servlet.api}</version>
<scope>provided</scope>
</dependency>
<!-- Jersey -->
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>${version.jersey}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
<version>${version.jersey}</version>
</dependency>
To deploy the application the minimal web.xml descriptor must be used:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<session-config>
<session-timeout>30</session-timeout>
<cookie-config>
<name>SESSIONID</name>
</cookie-config>
</session-config>
</web-app>
@Path("/message")
public class MessageResource {
@GET
@Path("ping")
public String getServerTime() {
return "received ping on "+new Date().toString();
}
@GET
@Produces({MediaType.APPLICATION_JSON}) //add MediaType.APPLICATION_XML if you want XML as well (don't forget @XmlRootElement)
public List<Message> getAllMessages() throws Exception{
List<Message> messages = new ArrayList<>();
Message firstMessage = new Message();
firstMessage.setDate(new Date());
firstMessage.setFirstName("Nabi");
firstMessage.setAge(30);
firstMessage.setText("Hello World!");
messages.add(firstMessage);
Message secondMessage = new Message();
secondMessage.setDate(new Date());
secondMessage.setFirstName("Francis");
secondMessage.setAge(31);
secondMessage.setText("It's in the game.");
messages.add(secondMessage);
return messages; //do not use Response object because this causes issues when generating XML automatically
}
@GET
@Produces({MediaType.APPLICATION_JSON}) //add MediaType.APPLICATION_XML if you want XML as well (don't forget @XmlRootElement)
@Path("text/{textParam}")
public Message getMessage(@PathParam("textParam") String textParam) throws Exception{
Message message = new Message();
message.setDate(new Date());
message.setFirstName("Vladimir");
message.setAge(35);
message.setText(textParam);
return message;
}
}
For testing, you can use one of the following clients:
Deploy the application to web server and go to the address http://localhost:8080/rest/: