A Guide to RESTEasy – RESTEasy指南

最后修改: 2016年 2月 16日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.介绍

JAX-RS (Java API for RESTful Web Services) is a set of Java API that provides support in creating REST APIs. And the framework makes good use of annotations to simplify the development and deployment of these APIs.

JAX-RS(Java API for RESTful Web Services)是一套Java API,它为创建REST API提供支持。该框架很好地利用了注解来简化这些API的开发和部署。

In this tutorial, we’ll use RESTEasy, the JBoss provided portable implementation of JAX-RS specification, in order to create a simple RESTful Web services.

在本教程中,我们将使用RESTEasy,即JBoss提供的JAX-RS规范的可移植实现,以创建一个简单的RESTful Web服务。

2. Project Setup

2.项目设置

We are going two consider two possible scenarios:

我们将考虑两种可能的情况。

  • Standalone Setup – intended for working on every application server
  • JBoss AS Setup – to consider only for deployment in JBoss AS

2.1. Standalone Setup

2.1.独立设置

Let’s start by using JBoss WildFly 10 with standalone setup.

让我们首先使用JBoss WildFly 10的独立设置。

JBoss WildFly 10 comes with RESTEasy version 3.0.11, but as you’ll see, we’ll configure the pom.xml with the new 3.0.14 version.

JBoss WildFly 10带有RESTEasy 3.0.11版本,但正如你将看到的,我们将用新的3.0.14版本配置pom.xml

And thanks to the resteasy-servlet-initializer, RESTEasy provides integration with standalone Servlet 3.0 containers via the ServletContainerInitializer integration interface.

而且由于resteasy-servlet-initializer,RESTEasy通过ServletContainerInitializer集成接口提供了与独立的Servlet 3.0容器的集成。

Let’s have a look at the pom.xml:

让我们看一下pom.xml

<properties>
    <resteasy.version>3.0.14.Final</resteasy.version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-servlet-initializer</artifactId>
        <version>${resteasy.version}</version>
    </dependency>
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-client</artifactId>
        <version>${resteasy.version}</version>
    </dependency>
</dependencies>

jboss-deployment-structure.xml

jboss-deployment-structure.xml

Within JBoss everything that is deployed as WAR, JAR or EAR is a module. These modules are referred to as dynamic modules.

在JBoss中,所有以WAR、JAR或EAR形式部署的东西都是一个模块。这些模块被称为动态模块

Beside these, there are also some static modules in $JBOSS_HOME/modules. As JBoss has the RESTEasy static modules – for standalone deployment, the jboss-deployment-structure.xml is mandatory in order to exclude some of them.

除了这些,还有一些静态模块$JBOSS_HOME/modules。由于JBoss有RESTEasy的静态模块–对于独立部署,jboss-deployment-structure.xml是必须的,以便排除其中的一些模块。

In this way, all classes and JAR files contained in our WAR will be loaded:

这样,我们的WAR中包含的所有类和JAR文件将被加载。

<jboss-deployment-structure>
    <deployment>
        <exclude-subsystems>
            <subsystem name="resteasy" />
        </exclude-subsystems>
        <exclusions>
            <module name="javaee.api" />
            <module name="javax.ws.rs.api"/>
            <module name="org.jboss.resteasy.resteasy-jaxrs" />
        </exclusions>
        <local-last value="true" />
    </deployment>
</jboss-deployment-structure>

2.2. JBoss as Setup

2.2.JBoss的设置

If you are going to run RESTEasy with JBoss version 6 or higher you can choose to adopt the libraries already bundled in the application server, thus simplifying the pom:

如果你打算在JBoss 6或更高版本中运行RESTEasy,你可以选择采用已经捆绑在应用服务器中的库,从而简化pom。

<dependencies>
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-jaxrs</artifactId>
        <version>${resteasy.version}</version>
    </dependency>
<dependencies>

Notice that jboss-deployment-structure.xml is no longer needed.

注意,jboss-deployment-structure.xml不再需要了。

3. Server Side Code

3.服务器端代码

3.1. Servlet Version 3 web.xml

3.1.Servlet Version 3 web.xml

Let’s now have a quick look at the web.xml of our simple project here:

现在让我们快速看一下我们这个简单项目的web.xml。

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
     http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

   <display-name>RestEasy Example</display-name>

   <context-param>
      <param-name>resteasy.servlet.mapping.prefix</param-name>
      <param-value>/rest</param-value>
   </context-param>

</web-app>

resteasy.servlet.mapping.prefix is needed only if you want prepend a relative path to the API application.

resteasy.servlet.mapping.prefix只有在你想给API应用程序预置相对路径时才需要。

At this point, it’s very important to notice that we haven’t declared any Servlet in the web.xml because resteasy servlet-initializer has been added as dependency in pom.xml. The reason for that is – RESTEasy provides org.jboss.resteasy.plugins.servlet.ResteasyServletInitializer class that implements javax.server.ServletContainerInitializer.

在这一点上,需要注意的是我们没有在web.xml中声明任何Servlet,因为resteasyservlet-initializer已经在pom.xml中作为依赖项加入。原因是–RESTEasy提供了org.jboss.resteasy.plugins.servlet.ResteasyServletInitializer类,实现了javax.server.ServletContainerInitializer

ServletContainerInitializer is an initializer and it’s executed before any servlet context will be ready – you can use this initializer to define servlets, filters or listeners for your app.

ServletContainerInitializer是一个初始化器,它在任何Servlet上下文准备好之前被执行 – 你可以使用这个初始化器来为你的应用程序定义Servlet、过滤器或监听器。

3.2. The Application Class

3.2.应用类

The javax.ws.rs.core.Application class is a standard JAX-RS class that you may implement to provide information on your deployment:

javax.ws.rs.core.Application类是一个标准的JAX-RS类,你可以实现它来提供你的部署信息。

@ApplicationPath("/rest")
public class RestEasyServices extends Application {

    private Set<Object> singletons = new HashSet<Object>();

    public RestEasyServices() {
        singletons.add(new MovieCrudService());
    }

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

As you can see – this is simply a class the lists all JAX-RS root resources and providers, and it is annotated with the @ApplicationPath annotation.

正如你所看到的–这只是一个列出所有JAX-RS根资源和提供者的类,并且它被注解为@ApplicationPath注解。

If you return any empty set for by classes and singletons, the WAR will be scanned for JAX-RS annotation resource and provider classes.

如果你返回任何空的by类和singletons集合,WAR将被扫描为JAX-RS注解资源和提供者类。

3.3. A Services Implementation Class

3.3.服务实现类

Finally, let’s see an actual API definition here:

最后,让我们在这里看到一个实际的API定义。

@Path("/movies")
public class MovieCrudService {

    private Map<String, Movie> inventory = new HashMap<String, Movie>();

    @GET
    @Path("/getinfo")
    @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
    public Movie movieByImdbId(@QueryParam("imdbId") String imdbId) {
        if (inventory.containsKey(imdbId)) {
            return inventory.get(imdbId);
        } else {
            return null;
        }
    }

    @POST
    @Path("/addmovie")
    @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
    public Response addMovie(Movie movie) {
        if (null != inventory.get(movie.getImdbId())) {
            return Response
              .status(Response.Status.NOT_MODIFIED)
              .entity("Movie is Already in the database.").build();
        }

        inventory.put(movie.getImdbId(), movie);
        return Response.status(Response.Status.CREATED).build();
    }
}

4. Conclusions

4.结论

In this quick tutorial we introduced RESTEasy and we built a super simple API with it.

在这个快速教程中,我们介绍了RESTEasy,并利用它构建了一个超级简单的API。

The example used in this article is available as a sample project in GitHub.

本文中使用的示例可作为GitHub中的示例项目