澤西島的 CRUD 運營示例
此示例演示瞭如何在 REST 資源上執行 CRUD 操作時使用 GET,POST,PUT 和 DELETE HTTP 方法
我使用以下軟體,框架和工具:
- 澤西島 2.25.1
- JDK 1.7.x(Java 7)
- Eclipse IDE Kepler
- Apache Maven 3.3.9
- Apache Tomcat 7.x
請按照以下步驟建立所需的澤西應用程式
步驟 1: 通過選擇 File-> New-> Maven Project,在 Eclipse IDE 中使用 maven-archetype-webapp 原型建立一個新的 maven 專案
第 2 步:在專案的 pom.xml 檔案中新增以下依賴項。
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<!-- if your container implements Servlet API older than 3.0, use "jersey-container-servlet-core" -->
<artifactId>jersey-container-servlet-core</artifactId>
<version>2.25.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-jaxb</artifactId>
<version>2.25.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.25.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
第 3 步:應用程式資源配置
建立一個擴充套件 org.glassfish.jersey.server.ResourceConfig 類的類,並在其建構函式中註冊 JAX-RS 元件。這裡我們在 com.stackoverflow.ws.rest 包下注冊所有資源。
package com.stackoverflow.ws.rest;
import org.glassfish.jersey.server.ResourceConfig;
public class MyApplication extends ResourceConfig {
public MyApplication() {
packages("com.stackoverflow.ws.rest");
}
}
第 4 步:使用 id 和 name 等屬性建立一個簡單的 Java bean,如 Employee。並覆蓋 equals()
和 hashCode()方法。此外,該類應該有一個無引數的公共建構函式。請找到以下程式碼:
員工 Java bean 類
package com.stackoverflow.ws.rest.model;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Employee {
private int id;
private String name;
public Employee(){
super();
}
public Employee(int id, String name) {
super();
this.id = id;
this.name = name;
}
@XmlElement
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@XmlElement
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Employee)) {
return false;
}
Employee other = (Employee) obj;
if (id != other.id) {
return false;
}
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
return true;
}
}
關於程式碼的一些額外資訊
- 註釋 @XmlRootElement 和 @XmlElement 是 JAXB 編組和解組請求和響應訊息所必需的。
第 5 步:建立員工資源,如下所示:
EmployeeResource 服務類
package com.stackoverflow.ws.rest;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import com.stackoverflow.ws.rest.model.Employee;
@Path("/employees")
public class EmployeeResource {
private static Map<Integer, Employee> employeesRepository = new HashMap<Integer, Employee>();
// Read - get all the employees
@GET
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response getEmployees() {
List<Employee> employees = new ArrayList<Employee>(
employeesRepository.values());
GenericEntity<List<Employee>> entity = new GenericEntity<List<Employee>>(
employees) {
};
return Response.ok(entity).build();
}
// Read - get an employee for the given ID
@GET
@Path("/{key}")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response getEmployee(@PathParam("key") int key) {
if (employeesRepository.containsKey(key)) {
return Response.ok(employeesRepository.get(key)).build();
} else {
return Response.status(404).build();
}
}
// Create - create an employee
@POST
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response addEmployee(Employee employee, @Context UriInfo uriInfo) {
if(employee.getId()!=0){
return Response.status(400).build();
}
int createdEmployeeId = 1;
if(!employeesRepository.isEmpty()){
createdEmployeeId = Collections.max(employeesRepository.keySet()) + 1;
}
employee.setId(createdEmployeeId);
employeesRepository.put(createdEmployeeId, employee);
UriBuilder builder = uriInfo.getAbsolutePathBuilder();
URI createdURI = builder.path(Integer.toString(createdEmployeeId)).build();
return Response.created(createdURI).build();
}
// Update - updates an existing employee
@PUT
@Path("/{key}")
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response updateEmployee(@PathParam("key") int key, Employee employee) {
int status = 0;
if (employeesRepository.containsKey(key)) {
// update employeeRepostory
employeesRepository.put(key, employee);
status = 204;
} else {
status = 404;
}
return Response.status(status).build();
}
// Delete - deletes an existing employee
@DELETE
@Path("/{key}")
public Response deleteEmployee(@PathParam("key") int key) {
employeesRepository.remove(key);
return Response.noContent().build();
}
// Delete - deletes all the employees
@DELETE
public Response deleteEmployees() {
employeesRepository.clear();
return Response.noContent().build();
}
}
注意: 儘管 POST 和 PUT 方法都可用於建立和/或更新資源,但我們在此限制 POST 方法更新現有資源和 PUT 方法以建立新資源。但要了解有關這些方法的更多資訊,請訪問此連結
步驟 6:最後在 Deployment Descriptor 檔案中新增 Jersey Servlet 配置(web.xml)
<web-app>
<display-name>Jersey 2.25.1 based REST Application</display-name>
<servlet>
<servlet-name>JerseyFrontController</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.stackoverflow.ws.rest.MyApplication</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>JerseyFrontController</servlet-name>
<url-pattern>/ws/rest/*</url-pattern>
</servlet-mapping>
</web-app>
步驟 7:在確保專案中的以下資料夾結構後,清理並構建專案。
步驟 8:在 Apache Tomcat 中執行應用程式。
現在,在 chrome 或 SOAP UI 中使用一些 REST 客戶端(如 POSTMAN 擴充套件)導航到 http:// {hostname}:{portnumber} / {projectName / applicationName} / ws / rest / employees,使用適當的 HTTP 方法,不要忘記在 HTTP 請求中新增帶有 application / json 或 application / xml 的 Accept 標頭作為值。 **** ****