jersey 是 sun 公司的一套HTTP接口,并不是真正的WebService。
由于采用了HTTP接口,自然就省去了SOAP封闭的步骤。
JSR绑定还是省不了的。
jersey在理解上最难的莫过于他的一套 Annotation 风格的代码。
将jersey放在Tomcat servlet中作服务端,这个代码很多。我喜欢嵌在Console程序中。
根据官方的
http://jersey.java.net/nonav/documentation/latest/getting-started.html
的非常明晰的DEMO。
以下程序是服务端。我这边根据项目上要求要用JSON来传递。
这样访问 http://localhost:9998/helloworld 会有明显的变化。
客户端就不多说了
由于采用了HTTP接口,自然就省去了SOAP封闭的步骤。
JSR绑定还是省不了的。
jersey在理解上最难的莫过于他的一套 Annotation 风格的代码。
将jersey放在Tomcat servlet中作服务端,这个代码很多。我喜欢嵌在Console程序中。
根据官方的
http://jersey.java.net/nonav/documentation/latest/getting-started.html
的非常明晰的DEMO。
以下程序是服务端。我这边根据项目上要求要用JSON来传递。
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.sun.grizzly.http.SelectorThread;
import com.sun.jersey.api.container.grizzly.GrizzlyWebContainerFactory;
public class Main {
public static void main(String[] argc) throws IllegalArgumentException, IOException {
final String baseUri = "http://localhost:9998/";
final Map<String, String> initParams = new HashMap<String, String>();
initParams.put("com.sun.jersey.config.property.packages",
"com.sun.jersey.samples.helloworld.resources");
System.out.println("Starting grizzly...");
SelectorThread threadSelector = GrizzlyWebContainerFactory.create(baseUri, initParams);
System.out.println(String.format(
"Jersey app started with WADL available at %sapplication.wadl\n"
+ "Try out %shelloworld\nHit enter to stop it...",
baseUri, baseUri));
System.in.read();
threadSelector.stopEndpoint();
System.exit(0);
}
}
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
@Path("/helloworld")
public class HelloWorld {
@POST
@Produces(MediaType.APPLICATION_JSON)
public JSONObject getClichedMessage(JSONObject param) throws JSONException {
System.out.println(param);
return param;
}
}
// @Produces(MediaType.APPLICATION_JSON)不加的话,客户端如果求返回的话,会解析不出//来。如果这个函数是void的话,则客户端访问取返回值时会返回 HTTP STATUS 205。
//参数JSONObject param 不需要加 Annotation也可以识别。
这样访问 http://localhost:9998/helloworld 会有明显的变化。
客户端就不多说了
package com.pt;
import javax.ws.rs.core.MediaType;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
public class JerClient {
public static void main(String[] argc) throws JSONException {
Client c = Client.create();
WebResource r=c.resource("http://localhost:9998/helloworld");
JSONObject obj = new JSONObject();
obj.put("a", "1");
obj.put("b", "2");
JSONObject response = r.type(MediaType.APPLICATION_JSON_TYPE).post(JSONObject.class, obj);
System.out.println(response.toString());
}
}