泽西岛的 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 标头作为值。 **** ****