Example to build Contact Manager using Jersey and Jquery Ajax
This is an example to build a Contact Manager using Jersey and jQuery Ajax.
Let’s start by writing the project dependencies (maven)
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>2.11</version>
</dependency>
<dependency>
<groupId>javax.xml</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.11</version>
</dependency>
Instead of Jackson we can use other libraries with Jersey. But I prefer using Jackson.
Now we need a Model and a service layer to access the data from the Jersey controllers.
Model class Contact annotated with JAXB annotations.
package com.sarath.ajax.models;import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;@XmlRootElement
public class Contact {@XmlElement
private long id;
@XmlElement
private String name;
@XmlElement
private String number;public Contact(long id, String name, String number) {
this.id = id;
this.name = name;
this.number = number;
}public Contact(){}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}public String toString(){
return "id : "+ id + "\n" + "name : "
+ name + "\n" + "number : "+ number;
}
}
A dummy service ContactService.
package com.sarath.ajax.services;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.sarath.ajax.models.Contact;
public class ContactService {
private static Map<Long, Contact> contacts = new HashMap<Long, Contact>();
public ContactService(){
}
public Contact getContact(long id){
return contacts.get(id);
}
public void save(Contact contact){
contacts.put(contact.getId(), contact);
}
public void update(Contact contact){
contacts.replace(contact.getId(), contact);
}
public void delete(long id){
contacts.remove(id);
}
public List getAllContacts(){
return new ArrayList(contacts.values());
}
}
Now everything is ready and we can begin writing the Jersey Application
First thing we need is a Config class for writing out configuration. In order to do this Jersey provides us a ResourceConfig class which can be extended to implement our configurations.
package com.sarath.ajax;
import org.glassfish.jersey.server.ResourceConfig;
public class MyApplication extends ResourceConfig {
public MyApplication(){
packages(true, "com.sarath.ajax.restcontrollers");
}
}
Now as usual a web.xml file for our Servlet 2.5 specification.
jersey-servlet
org.glassfish.jersey.servlet.ServletContainer
javax.ws.rs.Application
com.sarath.ajax.MyApplication
jersey-servlet
/rest/*
The custom configuration class which I have defined is passed to the JerseyServlet or the JerseyContainer via the init-param, which will be available to the servlet via the ServletConfig Object. See the commented section its another way to mention the package where your rest controllers reside.
Sometimes we need to send some message back to the client for that we can create a model Message
package com.sarath.ajax.models;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Message {
@XmlElement
private String message;
public Message(String message) {
this.message = message;
}
}
Jersey Controller class ContactController
package com.sarath.ajax.restcontrollers;
import java.io.StringReader;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sarath.ajax.models.Contact;
import com.sarath.ajax.models.Message;
import com.sarath.ajax.services.ContactService;
@Path("contact")
public class ContactController {
ContactService service = new ContactService();
@GET
@Produces(MediaType.TEXT_PLAIN)
public String helloWorld() {
return "Hello, World !";
}
@GET
@Path("/all")
@Produces(MediaType.APPLICATION_JSON)
public Response getAllContacts() {
List contacts = service.getAllContacts();
if(contacts.size() == 0){
return Response.noContent().build();
}
return Response.ok(contacts).build();
}
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response getContact(@PathParam("id") long id) {
Contact contact = service.getContact(id);
if (contact == null) {
return Response.noContent().build();
}
return Response.ok(contact).build();
}
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response createContact(@FormParam("name") String name,
@FormParam("number") String number, @FormParam("id") long id) {
Contact contact = new Contact(id, name, number);
service.save(contact);
return Response.ok(contact).build();
}
@PUT
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response updateContact(@FormParam("name") String name,
@FormParam("number") String number, @PathParam("id") long id) {
service.update(new Contact(id, name, number));
return Response.ok(new Message("Contact Updated")).build();
}
@PUT
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response updateContactUsingJson(/*Contact contact*/ String json){
boolean modified = false;
ObjectMapper mapper = new ObjectMapper();
try {
Contact contact = mapper.readValue(new StringReader(json), Contact.class);
System.out.println(contact.toString());
service.update(contact);
modified = true;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(modified){
return Response.ok(new Message("Contact Updated")).build();
} else {
return Response.ok(new Message("Contact cannot be updated")).build();
}
}
@DELETE
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response deleteContact(@PathParam("id") long id) {
service.delete(id);
return Response.ok(new Message("Contact Deleted")).build();
}
}
I’m not going into details of the class. Just refer Jersey documentation. My Intention is to give a small working Jersey + Jquery ajax application.
Now we have a perfect working backend.
Read similar articles from Keleno
Follow us on Linkedin