使用Jersey开发Resful的web Service的hello world

来源:互联网 发布:js new date精确到秒 编辑:程序博客网 时间:2024/05/29 17:10

RESTful Web 服务简介

  REST 在 2000 年由 Roy Fielding 在博士论文中提出,他是 HTTP 规范 1.0 和 1.1 版的首席作者之一。

  REST 中最重要的概念是资源(resources),使用全球 ID(通常使用 URI)标识。客户端应用程序使用 HTTP 方法(GET/ POST/ PUT/ DELETE)操作资源或资源集。RESTful Web 服务是使用 HTTP 和 REST 原理实现的 Web 服务。通常,RESTful Web 服务应该定义以下方面:

  Web 服务的基/根 URI,比如 http://host/<appcontext>/resources。

  支持 MIME 类型的响应数据,包括 JSON/XML/ATOM 等等。

  服务支持的操作集合(例如 POST、GET、PUT 或 DELETE)。

        构建 RESTful Web 服务

          @Path("/hello")

public class HelloResource

{

@GET

@Produces(MediaType.TEXT_PLAIN)

public String sayHello(){

return "hello jersey";

}

}

web.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>  
        <servlet-name>Jersey Web Application</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>Jersey Web Application</servlet-name>  
        <url-pattern>/rest/*</url-pattern>  
    </servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

所需jar包

jersey-core.jar,jersey-server.jar,jsr311-api.jar,asm.jar

客户端测试所需包,jersey-client.jar,junit-4.1.jar

测试:

网页上访问:http://localhost:8080/RestHello/rest/hello

  网页上显示

hello jersey
Junit测试,

@Test
public void getTest(){
Client c = Client.create();
WebResource hello = c.resource("http://localhost:8080/RestHello/rest/hello");
String s = hello.get(String.class);
System.out.println(s);
}

打印”hello jersey“