JAVA EE6 引入的一個新技術:JAX-RS(Java API for RESTful Web Services)。這是一個Java 編程語言的應用程序接口,支持按照表述性狀態轉移(REST)架構風格創建Web服務。它有好幾種實現方式,而Jersey是其參考實現方式。Jersey的詳細介紹請參考:Jersey官網。
說明:Jsersey默認使用maven框架,這裏假設你已經安裝好maven及tomcat服務。
一 新建測試項目
mvn archetype:generate -DarchetypeArtifactId=jersey-quickstart-webapp \
-DarchetypeGroupId=org.glassfish.jersey.archetypes -DinteractiveMode=false \
-DgroupId=com.example -DartifactId=simple-service-webapp -Dpackage=com.example \
-DarchetypeVersion=2.22.2
artifactId
,package
可以更換。package com.example;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
/**
* Root resource (exposed at "myresource" path)
*/
@Path("myresource")
public class MyResource {
/**
* Method handling HTTP GET requests. The returned object will be sent
* to the client as "text/plain" media type.
*
* @return String that will be returned as a text/plain response.
*/
@GET
@Produces(MediaType.TEXT_PLAIN)
public String getIt() {
return "Got it!";
}
}
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/webapi/*</url-pattern>
</servlet-mapping>
二 測試
mvn clean package
startup.bat
啓動成功後再瀏覽器中訪問:三 使用Json
<!-- uncomment this to get JSON support
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
</dependency>
-->
package com.example;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.xml.bind.annotation.*;
@Path("user/{username}")
@XmlRootElement
public class User {
public String name;
public int age;
public User(){}
public User(String name, int age){
this.name = name;
this.age = age;
}
@GET
@Produces("application/json")
public User getUser(@PathParam("username") String userName){
return new User(userName, 28);
}
}