登录站点

用户名

密码

基于JAX - RS(JSR311)规范开发RESTful Web服务

3已有 2493 次阅读  2011-12-02 11:01   标签JAX  restful 

开发的环境
{Jersey Tomcat   Maven Eclipse 3.7 }

(一)pom.xml的配置
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.company</groupId>
	<artifactId>rest</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>rest</name>
	<url>http://maven.apache.org</url>

<dependencies>
		<dependency>
			<groupId>com.sun.jersey</groupId>
			<artifactId>jersey-server</artifactId>
			<version>1.8</version>
		</dependency>
</dependencies>

<build>
		<finalName>api</finalName>
		<pluginManagement>
			<plugins>
	                  <plugin>
					<groupId>org.codehaus.mojo</groupId>
					<artifactId>tomcat-maven-plugin</artifactId>
					
					<configuration>
						<server>tomcat</server>
						<path>/api</path>
					</configuration>
					
				</plugin>
			</plugins>
		</pluginManagement>
	</build>
</project>

(二)编写MessageRestService
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

@Path("/message")
public class MessageRestService {

	@GET
	@Path("/{param}")
	public Response showMessage(@PathParam("param") String msg) {
		String result = "第一个rest应用:" + msg;
		return Response.status(200).entity(result).build();
	}

}
(三)配置web.xml
<web-app id="WebApp_ID" version="2.4"
	xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
		<display-name>API</display-name>
	
		<servlet>
		<servlet-name>jersey-serlvet</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>com.company.rest</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
 
	<servlet-mapping>
		<servlet-name>jersey-serlvet</servlet-name>
		<url-pattern>/rest/*</url-pattern>
	</servlet-mapping>
	</web-app>

(四)URL请求: http://localhost:8080/api/rest/message/HelloWorld



分享 举报