当前位置: 代码迷 >> Web前端 >> RESTEasy 入门范例
  详细解决方案

RESTEasy 入门范例

热度:499   发布时间:2013-07-01 12:33:04.0
RESTEasy 入门实例


1. 在Eclipse中建立Maven工程

1.1 新建Maven工程


1.2 选择默认工作空间


1.3 选择 maven-archetype-webapp Archetype


1.4 填写Group id,Artifact id,package


1.5 生成的web工程初始目录结构


2. 添加工程依赖
2.1 用Maven POM Editor 打开pom.xml文件,在Dependencies中添加依赖包


2.2 在查询栏中输入“resteasy-jaxrs”,在查询结果中选择版本3.0.0


2.3 保存pom.xml后,manvn从中央代码仓库自动下载依赖包


3. REST Service
package com.example.rest.resteasy.service;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

@Path("/hello")
public class HelloWorldRestService {

	@GET
	@Path("/{param}")
	public Response getName(@PathParam("param") String name) {
		String result = "RESTEasy Hello World : " + name;
		return Response.status(200).entity(result).build();
	}
}


4. Rest Application
package com.example.rest.resteasy.app;

import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.core.Application;
import com.example.rest.resteasy.service.HelloWorldRestService;

public class HelloWorldApplication extends Application {
	private Set<Object> singletons = new HashSet<Object>();

	public HelloWorldApplication() {
		singletons.add(new HelloWorldRestService());
	}

	@Override
	public Set<Object> getSingletons() {
		return singletons;
	}
}


5. web.xml
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
	<display-name>Archetype Created Web Application</display-name>

	<servlet>
		<servlet-name>resteasy-servlet</servlet-name>
		<servlet-class>
			org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
		</servlet-class>
		<init-param>
			<param-name>javax.ws.rs.Application</param-name>
			<param-value>com.example.rest.resteasy.app.HelloWorldApplication</param-value>
		</init-param>
	</servlet>

	<servlet-mapping>
		<servlet-name>resteasy-servlet</servlet-name>
		<url-pattern>/*</url-pattern>
	</servlet-mapping>
</web-app>


6. Run AS -> run jetty
在这个例子中,web请求“http://localhost:8080/resteasy-example/hello”将匹配HelloWorldRestService,“http://localhost:8080/resteasy-example/hello/{任意值}”将匹配到方法参数@PathParam 参数