RESTful系列文章索引
jersey是一个RESTful的框架, 属于glassfish项目.
官方网站: http://jersey.com/
jersey目前的中文文档比较少, 官方的例子使用了maven来构建. 使用tomcat的时候配置jar包比较麻烦, 可以参考官方文档中配置的内容.
本文内容都是参考官方文档.
什么是REST?
表象化状态转变(英文:Representational State Transfer,简称REST)是Roy Fielding博士在2000年他的博士论文中提出来的一种软件架构风格。
论文中文下载地址: REST_cn架构风格与基于网络的软件架构设计.pdf
需要注意的是,REST是设计风格而不是标准。REST通常基于使用HTTP,URI,和XML以及HTML这些现有的广泛流行的协议和标准。
- 资源是由URI来指定。
- 对资源的操作包括获取、创建、修改和删除资源,这些操作正好对应HTTP协议提供的GET、POST、PUT和DELETE方法。
- 通过操作资源的表形来操作资源。
- 资源的表现形式则是XML或者HTML,取决于读者是机器还是人,是消费web服务的客户软件还是web浏览器。当然也可以是任何其他的格式。
本文的例子是根据官方的例子, 所有jar包都已打包在源代码下载中了.
定义一个Resource
package test;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.Path;
// The Java class will be hosted at the URI path "/helloworld"
@Path("/helloworld")
public class HelloWorldResource {
// The Java method will process HTTP GET requests
@GET
// The Java method will produce content identified by the MIME Media
// type "text/plain"
@Produces("text/plain")
public String getClichedMessage() {
// Return some cliched textual content
return "Hello World, Fuck U!";
}
}
通过annotation来定义了获取该资源的方法是GET, 资源的MIME是文本"text/plain".
这个就是返回一个字符串给网页.
开启服务器
jersey可以跑在grizzly容器中, 也可以在tomcat或glassfish等容器中, grizzly是一个小型的容器, 可以用作测试和学习使用.
本例子使用的是grizzly容器
package test;
import com.sun.grizzly.http.SelectorThread;
import com.sun.jersey.api.container.grizzly.GrizzlyWebContainerFactory;
import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import javax.ws.rs.core.UriBuilder;
public class Main {
private static int getPort(int defaultPort) {
String port = System.getenv("JERSEY_HTTP_PORT");
if (null != port) {
try {
return Integer.parseInt(port);
} catch (NumberFormatException e) {
}
}
return defaultPort;
}
private static URI getBaseURI() {
return UriBuilder.fromUri("http://localhost/").port(getPort(9998)).build();
}
public static final URI BASE_URI = getBaseURI();
protected static SelectorThread startServer() throws IOException {
final Map<String, String> initParams = new HashMap<String, String>();
initParams.put("com.sun.jersey.config.property.packages",
"test");
System.out.println("Starting grizzly...");
SelectorThread threadSelector = GrizzlyWebContainerFactory.create(BASE_URI, initParams);
return threadSelector;
}
public static void main(String[] args) throws IOException {
SelectorThread threadSelector = startServer();
System.out.println(String.format("Jersey app started with WADL available at "
+ "%sapplication.wadl\nTry out %shelloworld\nHit enter to stop it...",
BASE_URI, BASE_URI));
System.in.read();
threadSelector.stopEndpoint();
}
}
右键运行java application即可看到
Starting grizzly...
2012-2-24 1:09:18 com.sun.grizzly.Controller logVersion
信息: Starting Grizzly Framework 1.9.18-i - Fri Feb 24 01:09:18 CST 2012
Jersey app started with WADL available at http://localhost:9998/application.wadl
Try out http://localhost:9998/helloworld
Hit enter to stop it...
在浏览器中输入http://localhost:9998/helloworld, 即可看到
Hello World, Fuck U!
这个就是我们之前定义的Resource.
在浏览器中输入http://localhost:9998/application.wadl, 可以看到
<application>
<doc jersey:generatedBy="Jersey: 1.8 06/24/2011 12:39 PM"/>
<resources base="http://localhost:9998/">
<resource path="/helloworld">
<method name="GET" id="getClichedMessage">
<response>
<representation mediaType="text/plain"/>
</response>
</method>
</resource>
</resources>
</application>
这个是资源的定义, web service的定义.
测试
我们可以不需要手动在浏览器或者其他方式获取每个连接的内容, 而是使用jersey提供的测试框架(基于JUnit).
package test;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.core.header.MediaTypes;
import com.sun.jersey.test.framework.JerseyTest;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Naresh
*/
public class MainTest extends JerseyTest {
public MainTest()throws Exception {
super("com.sun.jersey.samples.helloworld.resources");
}
/**
* Test to see that the message "Hello World" is sent in the response.
*/
@Test
public void testHelloWorld() {
WebResource webResource = resource();
String responseMsg = webResource.path("helloworld").get(String.class);
assertEquals("Hello World, Fuck U!", responseMsg);
}
/**
* Test if a WADL document is available at the relative path
* "application.wadl".
*/
@Test
public void testApplicationWadl() {
WebResource webResource = resource();
String serviceWadl = webResource.path("application.wadl").
accept(MediaTypes.WADL).get(String.class);
assertTrue(serviceWadl.length() > 0);
}
}
运行上述测试方法, 即可保证资源的获取是符合您资源的定义和您的意图.
结语
本文还有很多不足, 不是十分详细, 只是一个简单的例子, 可以体会jersey的使用. 如有错漏, 敬请指正!
示例源代码: JerseyDemo.zip