resteasy
Welcome to RESTEasy Tutorial. RESTEasy is the JAX-RS implementation provided by JBoss project. We can use RESTEasy to create restful web services. RESTEasy provides tighter integration with the JBoss Application Server but we can deploy it on any servlet container. So today we will learn how to create restful web service using RestEasy framework and deploy in Tomcat servlet container to test it.
欢迎使用RESTEasy教程。 RESTEasy是JBoss项目提供的JAX-RS实现。 我们可以使用RESTEasy创建宁静的Web服务。 RESTEasy提供了与JBoss Application Server的更紧密的集成,但是我们可以将其部署在任何servlet容器上。 因此,今天我们将学习如何使用RestEasy框架创建Restful Web服务并部署在Tomcat Servlet容器中进行测试。
Some of the features of RESTEasy framework are:
RESTEasy框架的一些功能包括:
Below are the URIs we will be exposing in our RestEasy web service implementation.
以下是我们将在RestEasy Web服务实现中公开的URI。
URI | HTTP Method | Description |
---|---|---|
/employee/add | POST | Add an employee |
/employee/getDummy | GET | returns a dummy employee object |
/employee/{id}/get | GET | Get the employee with ‘id’ in the URI |
/employee/getAll | GET | Get all employees |
/employee/{id}/delete | DELETE | Delete employee with ‘id’ in the URI |
URI | HTTP方法 | 描述 |
---|---|---|
/员工/添加 | 开机自检 | 新增员工 |
/员工/ getDummy | 得到 | 返回一个虚拟员工对象 |
/ employee / {id} / get | 得到 | 获取URI中带有“ id”的员工 |
/员工/ getAll | 得到 | 获取所有员工 |
/ employee / {id} / delete | 删除 | 删除URI中带有“ id”的员工 |
Below image shows our final project structure. First of all create a “Dynamic Web Application” in Eclipse and then convert it to Maven project to get the web project skeleton.
下图显示了我们的最终项目结构。 首先,在Eclipse中创建“动态Web应用程序”,然后将其转换为Maven项目以获取Web项目框架。
Let’s look into different components of our RestEasy web services project.
让我们研究一下RestEasy Web服务项目的不同组件。
We have two model classes – Employee
for employee object and GenericResponse
for sending client response object for status, message and error code.
我们有两个模型类– Employee
用于雇员对象, GenericResponse
用于发送客户端响应对象的状态,消息和错误代码。
package com.journaldev.jaxrs.model;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "employee")
public class Employee {
private String name;
private double salary;
private int id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return id + "::" + name + "::" + salary;
}
}
package com.journaldev.jaxrs.model;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "response")
public class GenericResponse {
private boolean status;
private String message;
private String errorCode;
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
@Override
public String toString() {
return status + "|" + message + "|" + errorCode;
}
}
Notice that both the java beans are annotated with @XmlRootElement
annotation. This is required for JAXB API for converting objects to xml and vice versa.
请注意,两个Java Bean都使用@XmlRootElement
注释进行了注释。 这是JAXB API所必需的,用于将对象转换为xml,反之亦然。
Let’s first create an interface for all the operations we are trying to expose in our restful web service.
首先,我们为尝试在静态Web服务中公开的所有操作创建一个接口。
package com.journaldev.jaxrs.service;
import javax.ws.rs.core.Response;
import com.journaldev.jaxrs.model.Employee;
public interface EmployeeService {
public Response addEmployee(Employee e);
public Response deleteEmployee(int id);
public Employee getEmployee(int id);
public Employee[] getAllEmployees();
}
Below is the implementation class for above employee service interface.
以下是上述员工服务接口的实现类。
package com.journaldev.jaxrs.service;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.journaldev.jaxrs.model.Employee;
import com.journaldev.jaxrs.model.GenericResponse;
@Path("/employee")
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
public class EmployeeServiceImpl implements EmployeeService {
private static Map emps = new HashMap();
@Override
@POST
@Path("/add")
public Response addEmployee(Employee e) {
GenericResponse response = new GenericResponse();
if(emps.get(e.getId()) != null){
response.setStatus(false);
response.setMessage("Employee Already Exists");
response.setErrorCode("EC-01");
return Response.status(422).entity(response).build();
}
emps.put(e.getId(), e);
response.setStatus(true);
response.setMessage("Employee created successfully");
return Response.ok(response).build();
}
@Override
@DELETE
@Path("/{id}/delete")
public Response deleteEmployee(@PathParam("id") int id) {
GenericResponse response = new GenericResponse();
if(emps.get(id) == null){
response.setStatus(false);
response.setMessage("Employee Doesn't Exists");
response.setErrorCode("EC-02");
return Response.status(404).entity(response).build();
}
emps.remove(id);
response.setStatus(true);
response.setMessage("Employee deleted successfully");
return Response.ok(response).build();
}
@Override
@GET
@Path("/{id}/get")
public Employee getEmployee(@PathParam("id") int id) {
return emps.get(id);
}
@GET
@Path("/{id}/getDummy")
public Employee getDummyEmployee(@PathParam("id") int id) {
Employee e = new Employee();
e.setSalary(8976.55);
e.setName("Dummy");
e.setId(id);
return e;
}
@Override
@GET
@Path("/getAll")
public Employee[] getAllEmployees() {
Set ids = emps.keySet();
Employee[] e = new Employee[ids.size()];
int i=0;
for(Integer id : ids){
e[i] = emps.get(id);
i++;
}
return e;
}
}
We are using only JAX-RS API annotations such as @Path
, @PathParam
, Response
etc. Notice that I am using javax.ws.rs.core.Response
as response object in some of the methods where I want to send the HTTP status code other than 200.
我们只使用JAX-RS API注释,比如@Path
, @PathParam
, Response
等。请注意,我用javax.ws.rs.core.Response
作为响应对象中的一些,我想发送的HTTP状态的方法200以外的代码。
We haven’t done anything related to RestEasy till now, it’s time now to configure RestEasy as our JAX-RS API implementation for our restful web service.
到目前为止,我们还没有做过与RestEasy相关的任何事情,现在是时候将RestEasy配置为我们的宁静Web服务的JAX-RS API实现。
First step is to extend javax.ws.rs.core.Application
class and override few of the methods to inject our service class implementation.
第一步是扩展javax.ws.rs.core.Application
类,并覆盖一些方法来注入我们的服务类实现。
package com.journaldev.jaxrs.resteasy.app;
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.core.Application;
import com.journaldev.jaxrs.service.EmployeeServiceImpl;
public class EmployeeApplication extends Application {
private Set
Next step is to add RESTEasy maven dependencies in our pom.xml file as shown below.
下一步是在pom.xml文件中添加RESTEasy Maven依赖项,如下所示。
org.jboss.resteasy
resteasy-jaxrs
3.0.13.Final
org.jboss.resteasy
resteasy-jaxb-provider
3.0.13.Final
Final step is to configure RESTEasy servlet class in deployment descriptor as front controller.
最后一步是在部署描述符中将RESTEasy Servlet类配置为前端控制器。
RestEasy-Example
org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
resteasy-servlet
org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
javax.ws.rs.Application
com.journaldev.jaxrs.resteasy.app.EmployeeApplication
resteasy-servlet
/*
That’s it. Our web service is ready. You can see how easy it was to plugin RestEasy as our JAX-RS implementation for restful web service.
而已。 我们的网络服务已准备就绪。 您可以看到将RestEasy插入为我们的JAX-RS实现以实现宁静的Web服务是多么容易。
I am using Chrome Postman extension to perform testing for our web service. Below are some of the test cases with response.
One common part is the headers in all the requests as shown in below image.
我正在使用Chrome Postman扩展程序对我们的网络服务进行测试。 以下是一些具有响应的测试案例。
如下图所示,所有请求中的标头都是一个共同的部分。
As you can see that all the tests passed with flying colors, our rest web service is working fine.
如您所见,所有测试都通过了测试,我们的其余Web服务运行正常。
As I mentioned earlier, RestEasy also provides API for testing rest web services through java program. For this we need to add another dependency in our pom.xml file.
如前所述,RestEasy还提供用于通过Java程序测试其余Web服务的API。 为此,我们需要在pom.xml文件中添加另一个依赖项。
org.jboss.resteasy
resteasy-client
3.0.13.Final
Below is the simple test program where I am testing our web service programmatically. I am providing example for testing GET, POST and DELETE HTTP methods.
下面是一个简单的测试程序,其中我正在以编程方式测试我们的Web服务。 我提供了测试GET,POST和DELETE HTTP方法的示例。
package com.journaldev.jaxrs.resteasy.client;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
import com.journaldev.jaxrs.model.Employee;
import com.journaldev.jaxrs.model.GenericResponse;
public class RestEasyTestClient {
public static void main(String[] args) {
ResteasyClient client = new ResteasyClientBuilder().build();
//GET example
ResteasyWebTarget getDummy = client.target("https://localhost:8080/RestEasy-Example/employee/99/getDummy");
Response getDummyResponse = getDummy.request().get();
String value = getDummyResponse.readEntity(String.class);
System.out.println(value);
getDummyResponse.close();
//POST example
ResteasyWebTarget add = client.target("https://localhost:8080/RestEasy-Example/employee/add");
Employee emp = new Employee();
emp.setId(50);emp.setName("Rick");emp.setSalary(1000);
Response addResponse = add.request().post(Entity.entity(emp, MediaType.APPLICATION_XML));
System.out.println(addResponse.readEntity(GenericResponse.class));
System.out.println("HTTP Response Code:"+addResponse.getStatus());
addResponse.close();
addResponse = add.request().post(Entity.entity(emp, MediaType.APPLICATION_XML));
System.out.println(addResponse.readEntity(GenericResponse.class));
System.out.println("HTTP Response Code:"+addResponse.getStatus());
addResponse.close();
//DELETE example
ResteasyWebTarget delete = client.target("https://localhost:8080/RestEasy-Example/employee/50/delete");
Response deleteResponse = delete.request().delete();
System.out.println(deleteResponse.readEntity(GenericResponse.class));
System.out.println("HTTP Response Code:"+deleteResponse.getStatus());
deleteResponse.close();
deleteResponse = delete.request().delete();
System.out.println(deleteResponse.readEntity(GenericResponse.class));
System.out.println("HTTP Response Code:"+deleteResponse.getStatus());
deleteResponse.close();
}
}
Below is the output produced by above RESTEasy client program.
以下是上述RESTEasy客户端程序产生的输出。
99 Dummy 8976.55
true|Employee created successfully|null
HTTP Response Code:200
false|Employee Already Exists|EC-01
HTTP Response Code:422
true|Employee deleted successfully|null
HTTP Response Code:200
false|Employee Doesn't Exists|EC-02
HTTP Response Code:404
That’s all for RESTEasy tutorial. RESTEasy is a very easy framework for creating Restful web services in java easily. You can download the project from below link and play around with it to learn more.
这就是RESTEasy教程的全部内容。 RESTEasy是一个非常简单的框架,可以轻松地在Java中创建Restful Web服务。 您可以从下面的链接下载该项目并进行试用以了解更多信息。
翻译自: https://www.journaldev.com/9189/resteasy-tutorial-eclipse-tomcat
resteasy