resteasy_Eclipse和Tomcat的RESTEasy教程

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容器中进行测试。

RESTEasy教程 (RESTEasy Tutorial)

Some of the features of RESTEasy framework are:

RESTEasy框架的一些功能包括:

  • JAX-RS API compliant – so mostly you need to plug it with JAX-RS API coding to create rest web services.

    兼容JAX-RS API-因此大多数情况下,您需要使用JAX-RS API编码将其插入以创建其余的Web服务。
  • Runs on almost any servlet container supporting Java 6 or higher

    在几乎所有支持Java 6或更高版本的servlet容器上运行
  • Provides support for writing client programs using JAX-RS 2.0 client API. We will look into test program too.

    提供对使用JAX-RS 2.0客户端API编写客户端程序的支持。 我们也会研究测试程序。
  • Rich set of providers – XML, JSON, YAML, Multipart, XOP, Atom, etc.

    丰富的提供程序集-XML,JSON,YAML,Multipart,XOP,Atom等
  • OAuth2 and Distributed SSO with JBoss AS7

    OAuth2和带有JBoss AS7的分布式SSO
  • EJB, Seam, Guice, Spring, and Spring MVC integration

    EJB,Seam,Guice,Spring和Spring MVC集成

RESTEasy示例 (RESTEasy Example)

Below are the URIs we will be exposing in our RestEasy web service implementation.

以下是我们将在RestEasy Web服务实现中公开的URI。

URIHTTP MethodDescription
/employee/addPOSTAdd an employee
/employee/getDummyGETreturns a dummy employee object
/employee/{id}/getGETGet the employee with ‘id’ in the URI
/employee/getAllGETGet all employees
/employee/{id}/deleteDELETEDelete employee with ‘id’ in the URI
URI HTTP方法 描述
/员工/添加 开机自检 新增员工
/员工/ getDummy 得到 返回一个虚拟员工对象
/ employee / {id} / get 得到 获取URI中带有“ id”的员工
/员工/ getAll 得到 获取所有员工
/ employee / {id} / delete 删除 删除URI中带有“ id”的员工

RESTEasy示例Eclipse项目 (RESTEasy Example Eclipse Project)

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服务项目的不同组件。

RESTEasy示例模型类 (RESTEasy Example Model Classes)

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,反之亦然。

RESTEasy示例服务类 (RESTEasy Example Service Classes)

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<Integer,Employee> emps = new HashMap<Integer,Employee>();
	
	@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<Integer> 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@PathParamResponse等。请注意,我用javax.ws.rs.core.Response作为响应对象中的一些,我想发送的HTTP状态的方法200以外的代码。

RESTEasy配置 (RESTEasy Configuration)

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<Object> singletons = new HashSet<Object>();

	public EmployeeApplication() {
		singletons.add(new EmployeeServiceImpl());
	}

	@Override
	public Set<Object> getSingletons() {
		return singletons;
	}

}

Next step is to add RESTEasy maven dependencies in our pom.xml file as shown below.

下一步是在pom.xml文件中添加RESTEasy Maven依赖项,如下所示。

<dependency>
	<groupId>org.jboss.resteasy</groupId>
	<artifactId>resteasy-jaxrs</artifactId>
	<version>3.0.13.Final</version>
</dependency>
<!-- Below dependency is for JAXB integration -->
<dependency>
	<groupId>org.jboss.resteasy</groupId>
	<artifactId>resteasy-jaxb-provider</artifactId>
	<version>3.0.13.Final</version>
</dependency>

Final step is to configure RESTEasy servlet class in deployment descriptor as front controller.

最后一步是在部署描述符中将RESTEasy Servlet类配置为前端控制器。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns="https://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="https://xmlns.jcp.org/xml/ns/javaee https://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>RestEasy-Example</display-name>
  <listener>
    <listener-class>
         org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
      </listener-class>
  </listener>
  <servlet>
    <servlet-name>resteasy-servlet</servlet-name>
    <servlet-class>
            org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
        </servlet-class>
    <init-param>
      <param-name>javax.ws.rs.Application</param-name>
      <param-value>com.journaldev.jaxrs.resteasy.app.EmployeeApplication</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>resteasy-servlet</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>
</web-app>

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服务是多么容易。

RESTEasy Restful Web服务测试 (RESTEasy Restful Web Service Test)

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扩展程序对我们的网络服务进行测试。 以下是一些具有响应的测试案例。
如下图所示,所有请求中的标头都是一个共同的部分。

  1. getDummy
    RESTEasy Example Tutorial  web service getDummy

    getDummy
  2. add
    RESTEasy web service add example tutorial


  3. get
    RESTEasy web service get example

    得到
  4. getAll
    RESTEasy web service getAll

    得到所有
  5. delete
    RESTEasy web service delete

    删除
  6. add error – HTTP response 422
    RESTEasy web service add error

    添加错误– HTTP响应422
  7. delete error – HTTP response 404
    RESTEasy web service delete error

    删除错误-HTTP响应404

As you can see that all the tests passed with flying colors, our rest web service is working fine.

如您所见,所有测试都通过了测试,我们的其余Web服务运行正常。

RestEasy Client – ResteasyClient示例 (RestEasy Client – ResteasyClient example)

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文件中添加另一个依赖项。

<dependency>
	<groupId>org.jboss.resteasy</groupId>
	<artifactId>resteasy-client</artifactId>
	<version>3.0.13.Final</version>
</dependency>

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客户端程序产生的输出。

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee><id>99</id><name>Dummy</name><salary>8976.55</salary></employee>
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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值