星期六, 4月 23, 2011

[JAVA] 快快樂樂學JAVA RESTful Service using Jersey

本文記錄如何在JAVA+TOMCAT下使用Jersey快速建立RESTful WebService :
感謝Owen血尿付出。

第一步:安裝Eclipse跟Tomcat 6.0.32
第二步:下載Jersey Library 1.6。官網http://jersey.java.net/
第三步:將下載的.jar檔放到Tomcat/lib
核心的lib asm-3.1.jar, jersey-core.jar, jersey-server.jar, jsr-311-api-1.0.jar



第四步:開啟Eclipse,新建一個Dynamic Web Project
第五步:修改專案內的YourProjectName/WebContent/WEB-INF/web.xml,新增以下內容

<servlet>
      <servlet-name>JerseyServlet</servlet-name>
      <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
      <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
      <servlet-name>JerseyServlet</servlet-name>
      <url-pattern>/services/*</url-pattern>
 </servlet-mapping>

第六步:第一個HelloWorld Restful API (支援GET / POST)




package stut.csie.sample;

import java.io.IOException;
import java.io.InputStream;

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.QueryParam;
import javax.ws.rs.core.MediaType;

import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

@Path("/helloWorld")
public class HelloWorld {
  
 @GET
 @Produces(MediaType.TEXT_PLAIN)
 public String getHelloWorld() {
   String response = "Hello World :)";
   return response;
 }
 
 @POST
 @Produces(MediaType.APPLICATION_JSON)
 public String postHelloWorld(InputStream requestBodyStream) {
   JSONObject json = new JSONObject();
   try {
    json.put("requestbody", this.convertRequestBODY2String(requestBodyStream));
   } catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   return json.toString();
 }
  
 @GET
 @Path("/{getparameter}")
 @Produces(MediaType.APPLICATION_JSON) 
 public String getByPathParameterAndQueryPath(
   @PathParam(value="getparameter") String getparameter,
   @QueryParam(value="q") String q) throws JSONException {
   System.out.println(getparameter);
   System.out.println(q);
   JSONObject json = new JSONObject();
   json.put("pathParameter", getparameter);
   json.put("q", q);
   return json.toString();
 }
  
 //convert request inputstream to string 
 private String convertRequestBODY2String(InputStream requestBodyStream){
    StringBuffer buffer = new StringBuffer();
    int bufferContent = 0;
    do
    {
     try {
      bufferContent = requestBodyStream.read();
      System.out.println(bufferContent);
      if(bufferContent > 0)
       buffer.append((char) bufferContent);
       
     } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    }while(bufferContent > 0 );
    return buffer.toString();
 }
 }

第七步:測試你的RESTFul API

方法一:取得get方法帶入的QueryString
GET:http://hostname:port/webname/services/helloWorld/mytest

output: mytest

方法二:呼叫get
GET:http://hostname:port/webname/services/helloWorld

output:
HelloWorld

方法三:呼叫post
POST:http://hostname:port/webname/services/helloWorld

RequestBody:
helloword

output:
{"requestbody":"helloword"}

service:為web.xml所定義的url rewrite pattern
helloWrold:為你定義的@Path參數

補充說明:
1.每個api內的method,如果都加上@Path參數後,就可以在往下切階層了

@POST
@Path("/post")
  @Produces(MediaType.APPLICATION_JSON)
 public String postHelloWorld(InputStream requestBodyStream) {
...
}

呼叫方法
http://hostname:port/webname/services/helloWorld/post

2.Jersey 參數使用說明

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.



Reference:
三步轻松实现java restful web services
用 Java 技术创建 RESTful Web 服务
Overview of JAX-RS 1.0 Features
REST with Java (JAX-RS) using Jersey - Tutorial
Handling multiparts in Restful applications using Jersey(進階)

2 則留言:

  1. 作者您好
    請問在getByPathParameterAndQueryPath中
    "q"參數如何傳入,或是要傳入第二個參數如何做
    謝謝

    回覆刪除
    回覆
    1. @Path("/{getparameter}/{getparameter2}")

      @PathParam(value="getparameter2") String getparameter2,

      刪除

留個話吧:)

其他你感興趣的文章

Related Posts with Thumbnails