CRUD RESTful webservice


Trong bài này mình sẻ use CRUD để thao tác cho việc (Create, Read, Update, Delete)) restful web service..

Project

Tạo một  new dynamic project  WS-RESTful-CRUD  và add các library của jersey và trong thư mục lib. và chúng ta change web.xml như sau


<?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_2_5.xsd" id="WebApp_ID" version="2.5">
 <display-name>WS-RESTful-JAXB</display-name>
 <welcome-file-list>
 <welcome-file>index.html</welcome-file>
 <welcome-file>index.htm</welcome-file>
 <welcome-file>index.jsp</welcome-file>
 <welcome-file>default.html</welcome-file>
 <welcome-file>default.htm</welcome-file>
 <welcome-file>default.jsp</welcome-file>
 </welcome-file-list>

 <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>thaihoanghai.jersey</param-value>
 </init-param>
 </servlet>

 <servlet-mapping>
 <servlet-name>Jersey REST Service</servlet-name>
 <url-pattern>/rest/*</url-pattern>
 </servlet-mapping>

</web-app>

Tiếp theo chúng ta 1 class Todo

 

</pre>
package thaihoanghai.jersey.todo.model;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Todo {
 private String id;
 private String summary;
 private String description;
 public Todo() {
 // TODO Auto-generated constructor stub
 }
 public Todo(String id, String summary) {
 this.id = id;
 this.summary = summary;
 }
 public String getId() {
 return id;
 }
 public void setId(String id) {
 this.id = id;
 }
 public String getSummary() {
 return summary;
 }
 public void setSummary(String summary) {
 this.summary = summary;
 }
 public String getDescription() {
 return description;
 }
 public void setDescription(String description) {
 this.description = description;
 }

}
<pre>

Tạo 1 Enum TodoDao  như sau :


package thaihoanghai.jersey.todo.dao;

import java.util.HashMap;
import java.util.Map;

import thaihoanghai.jersey.todo.model.Todo;

public enum TodoDao {
 instance;
 private Map<String, Todo> contentProvider = new HashMap<String, Todo>();

private TodoDao(){
 Todo todo = new Todo("1", "Learn REST");
 todo.setDescription("Reader https://thaihoanghai.wordpress.com/webservice");
 contentProvider.put("1", todo);

todo = new Todo("2", "Do something");
 todo.setDescription("Read complete https://thaihoanghai.wordpress.com");
 contentProvider.put("2", todo);
 }
 
 public Map<String, Todo> getModel(){
 return contentProvider;
 }
}

 

Tạo form HTML cho việc thực hiện add thêm 1 Todo object vào trong file 


<pre><!DOCTYPE html>
<html>
 <head>
  <title>Form to create a new resource</title>
 </head>
<body>
  <form action="../de.vogella.jersey.todo/rest/todos" method="POST">
  <label for="id">ID</label>
  <input name="id" />
  <br/>
  <label for="summary">Summary</label>
  <input name="summary" />
  <br/>
  Description:
  <TEXTAREA NAME="description" COLS=40 ROWS=6></TEXTAREA>
  <br/>
  <input type="submit" value="Submit" />
  </form>
</body>
</html></pre>

Tạo ra Rest Service như sau


package thaihoanghai.jersey.todo.resources;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.JAXBElement;

import thaihoanghai.jersey.todo.dao.TodoDao;
import thaihoanghai.jersey.todo.model.Todo;

public class TodoResource {
 @Context
 UriInfo uriInfo;

 @Context
 Request request;

 String id;

public TodoResource(UriInfo uriInfo, Request request, String id) {
 super();
 this.uriInfo = uriInfo;
 this.request = request;
 this.id = id;
 }

 // Application integration
 @GET
 @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
 public Todo getTodo(){
 Todo todo = TodoDao.instance.getModel().get(id);
 if(todo == null)
 throw new RuntimeException("Get: Todo with " + id + " not found");
 return todo;
 }

 // for the browser
 @GET
 @Produces(MediaType.TEXT_XML)
 public Todo getTodoHTML(){
 Todo todo = TodoDao.instance.getModel().get(id);
 if(todo==null)
 throw new RuntimeException( "Get: Todo with " + id + " not found");
 return todo;
 }

 @PUT
 @Consumes(MediaType.APPLICATION_XML)
 public Response putTodo(JAXBElement<Todo> todo){
 Todo c = todo.getValue();
 return putAndGetResponse(c);
 }

 @DELETE
 public void deleteTodo(){
 Todo c = TodoDao.instance.getModel().remove(id);
 if(c == null)
 throw new RuntimeException("Delete: Todo with " + id + " not found");
 }

 private Response putAndGetResponse(Todo todo) {
 Response res;
 if(TodoDao.instance.getModel().containsKey(todo.getId())) {
 res = Response.noContent().build();
 } else {
 res = Response.created(uriInfo.getAbsolutePath()).build();
 }
 TodoDao.instance.getModel().put(todo.getId(), todo);
 return res;
 }
}

Code cua class TodosResource :


package thaihoanghai.jersey.todo.resources;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.UriInfo;

import thaihoanghai.jersey.todo.dao.TodoDao;
import thaihoanghai.jersey.todo.model.Todo;
// Will map the resource to the URL todos
@Path("/todos")
public class TodosResource {

// Allows to insert contextual objects into the class,
 // e.g. ServletContext, Request, Response, UriInfo
 @Context
 UriInfo uriInfo;
 @Context
 Request request;
 // Return the list of todos to the user in the browser
 @GET
 @Produces(MediaType.TEXT_XML)
 public List<Todo> getTodosBrowser() {
 List<Todo> todos = new ArrayList<Todo>();
 todos.addAll(TodoDao.instance.getModel().values());
 return todos;
 }

// Return the list of todos for applications
 @GET
 @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
 public List<Todo> getTodos() {
 List<Todo> todos = new ArrayList<Todo>();
 todos.addAll(TodoDao.instance.getModel().values());
 return todos;
 }
 // retuns the number of todos
 // Use http://localhost:8080/de.vogella.jersey.todo/rest/todos/count
 // to get the total number of records
 @GET
 @Path("count")
 @Produces(MediaType.TEXT_PLAIN)
 public String getCount() {
 int count = TodoDao.instance.getModel().size();
 return String.valueOf(count);
 }

@POST
 @Produces(MediaType.TEXT_HTML)
 @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
 public void newTodo(@FormParam("id") String id,
 @FormParam("summary") String summary,
 @FormParam("description") String description,
 @Context HttpServletResponse servletResponse) throws IOException {
 Todo todo = new Todo(id,summary);
 if (description!=null){
 todo.setDescription(description);
 }
 TodoDao.instance.getModel().put(id, todo);

servletResponse.sendRedirect("../create_todo.html");
 }
 // Defines that the next path parameter after todos is
 // treated as a parameter and passed to the TodoResources
 // Allows to type http://localhost:8080/de.vogella.jersey.todo/rest/todos/1
 // 1 will be treaded as parameter todo and passed to TodoResource
 @Path("{todo}")
 public TodoResource getTodo(@PathParam("todo") String id) {
 return new TodoResource(uriInfo, request, id);
 }

}

 

Chúng ta run url sau : http://localhost:8080/WS-RESTful-CRUD/rest/todos

kết quả : 1

 

Cuối cùng chúng ta tạo ra client.


package test;
import java.net.URI;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;

import thaihoanghai.jersey.todo.model.Todo;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.representation.Form;

public class Tester {
 public static void main(String[] args) {
 ClientConfig config = new DefaultClientConfig();
 Client client = Client.create(config);
 WebResource service = client.resource(getBaseURI());
 // Create one todo
 Todo todo = new Todo("3", "Blabla");
 ClientResponse response = service.path("rest").path("todos")
 .path(todo.getId()).accept(MediaType.APPLICATION_XML)
 .put(ClientResponse.class, todo);
 // Return code should be 201 == created resource
 System.out.println(response.getStatus());
 // Get the Todos
 System.out.println(service.path("rest").path("todos")
 .accept(MediaType.TEXT_XML).get(String.class));
 // Get JSON for application
 System.out.println(service.path("rest").path("todos")
 .accept(MediaType.APPLICATION_JSON).get(String.class));
 // Get XML for application
 System.out.println(service.path("rest").path("todos")
 .accept(MediaType.APPLICATION_XML).get(String.class));

// Get the Todo with id 1
 System.out.println(service.path("rest").path("todos/1")
 .accept(MediaType.APPLICATION_XML).get(String.class));
 // get Todo with id 1
 service.path("rest").path("todos/1").delete();
 // Get the all todos, id 1 should be deleted
 System.out.println(service.path("rest").path("todos")
 .accept(MediaType.APPLICATION_XML).get(String.class));

// Create a Todo
 Form form = new Form();
 form.add("id", "4");
 form.add("summary", "Demonstration of the client lib for forms");
 response = service.path("rest").path("todos")
 .type(MediaType.APPLICATION_FORM_URLENCODED)
 .post(ClientResponse.class, form);
 System.out.println("Form response " + response.getEntity(String.class));
 // Get the all todos, id 4 should be created
 System.out.println(service.path("rest").path("todos")
 .accept(MediaType.APPLICATION_XML).get(String.class));

}

private static URI getBaseURI() {
 return UriBuilder.fromUri("http://localhost:8080/WS-RESTful-CRUD").build();
 }
}

 

OK zậy là xong rồi . Chúng các bạn thành công :

nguồn : http://www.vogella.com

 

One Response to “CRUD RESTful webservice”

  1. kobee Says:

    <servlet>
    <servlet-name>Jersey Web Application</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
    <param-name>jersey.config.server.provider.packages</param-name>
    <param-value>thaihoanghai.hibernate.service</param-value>
    </init-param>
    <init-param>
    <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
    <param-value>true</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
    </servlet>

    <dependency>
    <groupId>com.fasterxml.jackson.jaxrs</groupId>
    <artifactId>jackson-jaxrs-json-provider</artifactId>
    <version>2.2.3</version>
    </dependency>


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: