restfull环境搭建-helloword

时间:2023-03-09 17:04:40
restfull环境搭建-helloword

原文地址:http://blog.csdn.net/u013158799/article/details/39758341

1. REST和RESTful Web Services的简要说明

REST(RepresentationalState Transfer),中文称为表述性状态转移,是一种针对于网络应用开发的软件架构风格,是满足一定的架构约束条件的。REST包括的准则主要有:

1)网络上所有事物都抽象成资源;

2)每个资源对应唯一的URI;

3)通过通用接口对资源操作;

5)操作都是无状态的;

RESTfulWeb Services,这是基于REST和HTTP实现的Web服务,在其实现的时候定义了URI,对资源的操作,以及支持的MIME类型等。

2.  JAX-RS和Jersey的简要说明:

JAX-RS,或称JSR311,是帮助实现RESTful WebServices的一组API,而Jersey则是其参考实现。下载地址:链接:http://pan.baidu.com/s/1c2MVCJm 密码:oy27

3. 开发环境配置:

Eclipse: 需要能进行Web Service开发的版本,例如《Eclipse IDE forJava EE Developers》

Tomcat:Tomcat是作为Web应用程序的服务器而使用的,为了在本次开发中能正确开发并调试程序,需要在Eclipse上预先配置Tomcat

4. HelloWord搭建:

步骤一:

新建Eclipse工程:“File->New->Other->DynamicWeb Project”,此处将工程命名为Restfull,之后的配置大约如下,具体需要注意Target runtime需要指定为对应的Tomcat版本,例如此处是7.0;

步骤二:将刚才下载的全部jar包复制到工程目录下,WEB-INF文件夹下的lib中,如图所示;

restfull环境搭建-helloword

步骤三:新建包用于存放所有资源,此处命名为sample.hello.resources,并新建类HelloResource(此资源仅用于测试,之后可以删除),代码如下:

package sample.hello.resources;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType; @Path("hello")
public class HelloResource { @GET
@Produces(MediaType.TEXT_PLAIN)
public String sayHello(){
return "hello,jersey";
} }

其中,@Path即定义了资源的URI,@Get即HTTP的Get方法,@Produces声明了相应内容的MIME类型;

步骤四:修改WEB-INF下的web.xml文件,内容改为:

<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Restfull</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>jersey REST Service</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>sample.hello.resources</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping> </web-app>

之后就可以尝试启动Tomcat,并在浏览器中输入:http://your_domain:port/display-name/url-pattern/path_from_rest_class以访问资源了,例到目前为止,要访问HelloResource则需要进入http://localhost:8080/Restfull/rest/hello.成功的话,则浏览器返回‘Hello Jersey’.效果如下图所示:

restfull环境搭建-helloword

工程源码下载地址:链接:http://pan.baidu.com/s/1slrxedn 密码:9hnm