jersey面向資源開發1
1.新建一個實體類package com.example.domain;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "device")
public class Device {
private String deviceIp;
private int deviceStatus;
public Device() {
}
public Device(String deviceIp) {
super();
this.deviceIp = deviceIp;
}
@XmlAttribute
public String getIp() {
return deviceIp;
}
public void setIp(String deviceIp) {
this.deviceIp = deviceIp;
}
@XmlAttribute
public int getStatus() {
return deviceStatus;
}
public void setStatus(int deviceStatus) {
this.deviceStatus = deviceStatus;
}
}
其中@XmlRootElement(name = "device")代表xml文件的根節點
其中@XmlRootElement(name = "device")代表xml文件的根節點
@XmlAttribute代表xml文件的屬性節點
在pom.xml文件中依賴下面2包
在pom.xml文件中依賴下面2包
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-grizzly2-http</artifactId>
</dependency>
<!-- get JSON support: -->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.9</version>
<scope>test</scope>
</dependency>
</dependencies>
在服務類中編寫
在服務類中編寫
package com.example;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.example.domain.Device;
@Path("myresource")
public class MyResource {
@GET
@Produces({ MediaType.APPLICATION_JSON })
public Device getIt() {
Device d=new Device("1.1.1.1");
d.setStatus(2);
return d;
}
}
建立測試類:
建立測試類:
package com.example;
import java.io.IOException;
import java.net.URI;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.glassfish.jersey.server.ResourceConfig;
public class Main {
public static final String BASE_URI = "http://localhost:8080/myapp/";
public static HttpServer startServer() {
final ResourceConfig rc = new ResourceConfig().packages("com.example");
return GrizzlyHttpServerFactory.createHttpServer(URI.create(Main.BASE_URI), rc);
}
public static void main(String[] args) throws IOException {
final HttpServer server = Main.startServer();
}
}
啟動后在瀏覽器中輸入http://localhost:8080/myapp/myresource,頁面返回
啟動后在瀏覽器中輸入http://localhost:8080/myapp/myresource,頁面返回
{"ip":"1.1.1.1","status":2} 返回json格式的數據。