วันพุธที่ 15 กุมภาพันธ์ พ.ศ. 2555

RESTful Webservices with Java (Jersey / JAX-RS) ตอนที่ 1

สวัสดีครับ ทุึกคน วันนี้ก็ถึงเวลาที่เราจะมาทดลองการเขียน Webservice กันสักที


Table 1. Sample Table
AnnotationDescription
@PATH(your_path)Sets the path to base URL + /your_path. The base URL is based on your application name, the servlet and the URL pattern from the web.xml" configuration file.
@POSTIndicates that the following method will answer to a HTTP POST request
@GETIndicates that the following method will answer to a HTTP GET request
@PUTIndicates that the following method will answer to a HTTP PUT request
@DELETEIndicates that the following method will answer to a HTTP DELETE request
@Produces( MediaType.TEXT_PLAIN [, more-types ] )@Produces defines which MIME type is delivered by a method annotated with @GET. In the example text ("text/plain" ) is produced. Other examples would be "application/xml" or "application/json".
@Consumes( type [, more-types ] )@Consumes defines which MIME type is consumed by this method.
@PathParamUsed to inject values from the URL into a method parameter. This way you inject for example the ID of a resource into the method to get the correct object.
The complete path to a resource is therefore based on the base URL and the @PATh annotation in your class.
http://your_domain:port/display-name/url-pattern/path_from_rest_class
   



Tools ที่เราใช้ประกอบไปด้วย
1. Eclipse Helios
2. Tomcat 6.0


1.Create Java Web Dynamic



























library ทั้งหมดที่เกี่ยวข้อง



cccc























1.Domain


package com.blogspot.javathaitalk.domain;


public class Track {


String title;
String singer;


public String getTitle() {
return title;
}


public void setTitle(String title) {
this.title = title;
}


public String getSinger() {
return singer;
}


public void setSinger(String singer) {
this.singer = singer;
}


@Override
public String toString() {
return "Track [title=" + title + ", singer=" + singer + "]";
}


}

2.Java Class Service


package com.blogspot.javathaitalk.webservices.rest;


import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;


import com.blogspot.javathaitalk.domain.Track;






@Path("/json/metallica")
public class JSONService {


@GET
@Path("/get")
@Produces(MediaType.APPLICATION_JSON)
public Track getTrackInJSON() {


Track track = new Track();
track.setTitle("Enter Sandman");
track.setSinger("Metallica");


return track;


}


@POST
@Path("/post")
@Consumes(MediaType.APPLICATION_JSON)
public Response createTrackInJSON(Track track) {


String result = "Track saved : " + track;
return Response.status(201).entity(result).build();

}

}


3.Jersey Client Get


package com.blogspot.javathaitalk.webservices.client;


import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;


public class JerseyClientGet {


public static void main(String[] args) {
try {


Client client = Client.create();


WebResource webResource = client.resource("http://localhost:8080/DemoRESTfulExample/rest/json/metallica/get");


ClientResponse response = webResource.accept("application/json")
.get(ClientResponse.class);


if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}


String output = response.getEntity(String.class);


System.out.println("Output from Server .... \n");
System.out.println(output);


} catch (Exception e) {


e.printStackTrace();


}


}


}

4.Jersey Client Post


package com.blogspot.javathaitalk.webservices.client;


import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;


public class JerseyClientPost {


public static void main(String[] args) {


try {


Client client = Client.create();


WebResource webResource = client
.resource("http://localhost:8080/DemoRESTfulExample/rest/json/metallica/post");


String input = "{\"singer\":\"Metallica\",\"title\":\"Fade To Black\"}";


ClientResponse response = webResource.type("application/json")
.post(ClientResponse.class, input);


if (response.getStatus() != 201) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}


System.out.println("Output from Server .... \n");
String output = response.getEntity(String.class);
System.out.println(output);


} catch (Exception e) {


e.printStackTrace();


}


}


}

 5.Define Jersey Servlet dispatcher


<?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>DemoRESTfulExample</display-name>
  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <servlet>
<servlet-name>jersey-serlvet</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>com.blogspot.javathaitalk.webservices.rest</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>


<servlet-mapping>
<servlet-name>jersey-serlvet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>

</web-app>




สำหรับการทดสอบ Webservice ให้ทำการ Run Java Web ก่อน แล้วค่อยไปเรียกทดสอบ Client แบบ java App ธรรมดาทีหลัง

1.ทดสอบ เรียกผ่าน URL ด้วย Get Method






2.ทดสอบเรียกผ่าน JerseyClientGet Class










3.ทดสอบเรียกผ่าน JerseyClientPost Class










*ปล. ถ้าใครอยากได้ SourceCode ให้ Comment ไว้นะครับ เดี๋ยวผมจะส่งให้ทาง Email.