Explore Jersey Request Parameters – 探索泽西岛请求参数

最后修改: 2019年 5月 28日

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

1. Introduction

1.绪论

Jersey is a popular Java framework for creating RESTful web services.

Jersey 是一个流行的Java框架,用于创建RESTful Web服务。

In this tutorial, we’ll explore how to read different request parameter types via a simple Jersey project.

在本教程中,我们将探讨如何通过一个简单的Jersey项目读取不同的请求参数类型。

2. Project Setup

2.项目设置

Using Maven archetypes, we’ll be able to generate a working project for our article:

使用Maven原型,我们就能为我们的文章生成一个工作项目。

mvn archetype:generate -DarchetypeArtifactId=jersey-quickstart-grizzly2
  -DarchetypeGroupId=org.glassfish.jersey.archetypes -DinteractiveMode=false
  -DgroupId=com.example -DartifactId=simple-service -Dpackage=com.example
  -DarchetypeVersion=2.28

The generated Jersey project will run on top of a Grizzly container.

生成的Jersey项目将在Grizzly容器之上运行。

Now, by default, the endpoint for our app will be http://localhost:8080/myapp.

现在,默认情况下,我们应用程序的端点将是http://localhost:8080/myapp.

Let’s add an items resource, which we’ll use for our experiments:

让我们添加一个items资源,我们将使用它来进行实验。

@Path("items")
public class ItemsController {
    // our endpoints are defined here
}

Note, by the way, that Jersey also works great with Spring controllers.

顺便注意,Jersey与Spring控制器的配合也非常好

3. Annotated Parameters Types

3.注释的参数类型

So, before we actually read any request parameters, let’s clarify a few rules. The allowed types of parameters are:

因此,在我们实际读取任何请求参数之前,让我们澄清一些规则。允许的参数类型有:

  • Primitive types, like float and char
  • Types that have a constructor with a single String argument
  • Types that have either a fromString or valueOf static method; for those, a single String argument is mandatory
  • Collections – like List, Set, and SortedSet – of the types described above

Also, we can register an implementation of the ParamConverterProvider JAX-RS extension SPI. The return type must be a ParamConverter instance capable of a conversion from a String to a type.

另外,我们可以注册一个ParamConverterProviderJAX-RS扩展SPI的实现。返回类型必须是一个ParamConverter实例,能够从String转换到一个类型。

4. Cookies

4.饼干

We can resolve cookie values in our Jersey methods using the @CookieParam annotation:

我们可以使用@CookieParam注解在我们的Jersey方法中解析cookie值

@GET
public String jsessionid(@CookieParam("JSESSIONId") String jsessionId) {
    return "Cookie parameter value is [" + jsessionId+ "]";
}
If we start up our container, we can cURL this endpoint to see the response:
> curl --cookie "JSESSIONID=5BDA743FEBD1BAEFED12ECE124330923" http://localhost:8080/myapp/items
Cookie parameter value is [5BDA743FEBD1BAEFED12ECE124330923]

5. Headers

5.头条新闻

Or, we can resolve HTTP headers with the @HeaderParam annotation:

或者,我们可以用@HeaderParam注解来解决HTTP头文件

@GET
public String contentType(@HeaderParam("Content-Type") String contentType) {
    return "Header parameter value is [" + contentType+ "]";
}

Let’s test again:

让我们再测试一下。

> curl --header "Content-Type: text/html" http://localhost:8080/myapp/items
Header parameter value is [text/html]

6. Path Parameters

6.路径参数

Especially with RESTful APIs, it’s common to include information in the path.

特别是对于RESTful API,在路径中包含信息是很常见的。

We can extract path elements with @PathParam:

我们可以用@PathParam提取路径元素。

@GET
@Path("/{id}")
public String itemId(@PathParam("id") Integer id) {
    return "Path parameter value is [" + id + "]";
}

Let’s send another curl command with the value 3:

让我们再发送一条curl命令,值为3

> curl http://localhost:8080/myapp/items/3
Path parameter value is [3]

7. Query Parameters

7.查询参数

We commonly use query parameters in RESTful APIs for optional information.

我们通常在RESTful API中使用查询参数来获取可选信息。

To read such values we can use the @QueryParam annotation:

为了读取这样的值,我们可以使用@QueryParam注解。

@GET
public String itemName(@QueryParam("name") String name) {
    return "Query parameter value is [" + name + "]";
}

So, now we can test with curl, like before:

所以,现在我们可以像以前一样,用curl进行测试。

> curl http://localhost:8080/myapp/items?name=Toaster
Query parameter value if [Toaster]

8. Form Parameters

8.表格参数

For reading parameters from a form submission, we’ll use the @FormParam annotation:
@POST
public String itemShipment(@FormParam("deliveryAddress") String deliveryAddress, 
  @FormParam("quantity") Long quantity) {
    return "Form parameters are [deliveryAddress=" + deliveryAddress+ ", quantity=" + quantity + "]";
}

We also need to set the proper Content-Type to mimic the form submission action. Let’s set the form parameters using the -d flag:

我们还需要设置适当的Content-Type来模仿表单提交动作。让我们使用-d标记来设置表单参数:

> curl -X POST -H 'Content-Type:application/x-www-form-urlencoded' \
  -d 'deliveryAddress=Washington nr 4&quantity=5' \
  http://localhost:8080/myapp/items
Form parameters are [deliveryAddress=Washington nr 4, quantity=5]

9. Matrix Parameters

9.矩阵参数

A matrix parameter is a more flexible query parameter as they can be added anywhere in the URL.

矩阵参数是一个更灵活的查询参数,因为它们可以被添加到URL的任何地方。

For example, in http://localhost:8080/myapp;name=value/items, the matrix parameter is name.

例如,在http://localhost:8080/myapp;name=value/items,矩阵参数为name

To read such values, we can use the available @MatrixParam annotation:

为了读取这样的值,我们可以使用可用的@MatrixParam注解。

@GET
public String itemColors(@MatrixParam("colors") List<String> colors) {
    return "Matrix parameter values are " + Arrays.toString(colors.toArray());
}

And now we’ll test again our the endpoint:

现在我们再测试一下我们的端点。

> curl http://localhost:8080/myapp/items;colors=blue,red
Matrix parameter values are [blue,red]

10. Bean Parameters

10.Bean参数

Finally, we’ll check how to combine request parameters using bean parameters. To clarify, a bean parameter is actually an object that combines different types of request parameters.

最后,我们将检查如何使用Bean参数来组合请求参数。为了澄清,bean参数实际上是一个结合了不同类型请求参数的对象。

We’ll use a header parameter, a path and a form one in here:

我们将在这里使用一个标题参数、一个路径和一个表单参数。

public class ItemOrder {
    @HeaderParam("coupon")
    private String coupon;

    @PathParam("itemId")
    private Long itemId;

    @FormParam("total")
    private Double total;

    //getter and setter

    @Override
    public String toString() {
        return "ItemOrder {coupon=" + coupon + ", itemId=" + itemId + ", total=" + total + '}';
    }
}

Also, to get such a combination of parameters, we’ll use the @BeanParam annotation:

另外,为了获得这样的参数组合,我们将使用@BeanParam注解。

@POST
@Path("/{itemId}")
public String itemOrder(@BeanParam ItemOrder itemOrder) {
    return itemOrder.toString();
}

In the curl command, we’ve added those three types of parameters and we’ll end up with a single ItemOrder object:

curl命令中,我们加入了这三种类型的参数,最后我们会得到一个ItemOrder对象。

> curl -X POST -H 'Content-Type:application/x-www-form-urlencoded' \
  --header 'coupon:FREE10p' \
  -d total=70 \
  http://localhost:8080/myapp/items/28711
ItemOrder {coupon=FREE10p, itemId=28711, total=70}

11. Conclusion

11.结语

To sum it up, we’ve created a simple setup for a Jersey project to help us explore how to read different parameters from a request using Jersey.

总结一下,我们已经为Jersey项目创建了一个简单的设置,以帮助我们探索如何使用Jersey从请求中读取不同的参数。

The implementation of all these snippets is available over on Github.

所有这些片段的实现都可以在Github上找到