本範例實作說明:
本篇主要使用 Restful,做一個基本測試專案
一、範例開發準備工具
作業系統: Windows 7
開發工具: Eclipse Java EE IDE for Web Developers Juno Service Release2
JAVA JDK : JDK1.7.0_52
其它相關: Maven 4.0
Resteasy Version 3.0.6.Final
二、新增Maven範例專案
範例專案名稱:RestfulSample
1.建立一個新的Maven Project
2.勾選Create a simple project(skip archetype selection)後按下Next按鈕
3.填入GroupId,ArtifactId以及選擇 Packaging 後按Next
4.產生後結果 project 結構
5. 手動新增WEB_INF folder結果
三、編輯 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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.sample.rest.resteasy</groupId> <artifactId>RestfulSample</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <dependency> <groupId>org.jboss.resteasy</groupId> <artifactId>resteasy-jaxrs</artifactId> <version>3.0.6.Final</version> </dependency> </dependencies> </project>
四、編輯 web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <context-param> <param-name>resteasy.scan</param-name> <param-value>true</param-value> </context-param> <context-param> <param-name>resteasy.servlet.mapping.prefix</param-name> <param-value>/rest</param-value> </context-param> <listener> <listener-class> org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap </listener-class> </listener> <servlet> <servlet-name>resteasy-servlet</servlet-name> <servlet-class> org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher </servlet-class> </servlet> <servlet-mapping> <servlet-name>resteasy-servlet</servlet-name> <url-pattern>/rest/*</url-pattern> </servlet-mapping> </web-app>五、編輯 MessageApplication.java
package com.sample.rest.app; import java.util.HashSet; import java.util.Set; import javax.ws.rs.core.Application; import com.sample.rest.MessageRestService; public class MessageApplication extends Application { private Set<Object> singletons = new HashSet<Object>(); public MessageApplication() { singletons.add(new MessageRestService()); } @Override public Set<Object> getSingletons() { return singletons; } }
六、編輯 MessageRestService.java
package com.sample.rest; 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 printMessage(@PathParam("param") String msg) { String result = "Restful example : " + msg; return Response.status(200).entity(result).build(); } }
六、結果顯示 :
URL = http://127.0.0.1:8080/RestfulSample/rest/message/puma
其它文章
沒有留言:
張貼留言