---
title: "RESTEasy 系列 Chapter 4 使用 @Path and @GET, @POST, 等"
author: "smallplum"
date: "2013-03-27T19:35:57Z"
tags: []
categories: ["开源软件"]
slug: "resteasy-chapter-4-path-and-get-post"
draft: false
lastmod: "2013-03-27T19:38:42Z"
id: 1837542
url: "https://essay.iteye.com/blog/1837542"
---

```
@Path("/library")
public class Library {
 
    @GET
    @Path("/books")
    public String getBooks() {...}
 
    @GET
    @Path("/book/{isbn}")
    public String getBook(@PathParam("isbn") String id) {
        // search my database and get a string representation and return it
    }
 
    @PUT
    @Path("/book/{isbn}")
    public void addBook(@PathParam("isbn") String id, @QueryParam("name") String name) {...}
 
    @DELETE
    @Path("/book/{id}")
    public void removeBook(@PathParam("id") String id {...}
 
 
}
```

 

 

比方说，如果你拥有Resteasy的servlet配置并且得到一个根路径http://myhost.com/services。

 

Library类的请求将被处理：

- GET http://myhost.com/services/library/books
- GET http://myhost.com/services/library/book/333
- PUT http://myhost.com/services/library/book/333
- DELETE http://myhost.com/services/library/book/333

@javax.ws.rs.Path注解必须存在于类和/或资源方法。如果类和方法都存在，这个资源方法的相对路径是连接类和方法。

在@javax.ws.rs包注解的每个HTTP方法，@GET, @POST, @PUT, @DELETE, 和 @HEAD。你可以将这些公共方法映射到某些想要的HTTP方法。只要有一个@Path注解在类上，你要映射的方法不用再有@Path注解。你可以有一个以上的HTTP方法，只要它们能区别于其它的方法。

当你有一个@Path注解的不是HTTP的方法，它们被叫做JAXRSResourceLocators。

 

**4.1. @Path和正则表达式映射**

 

@Path 注解不限于简单的路径表达式。你也能够插入正则表达式到@Path的value。示例：

 

```
@Path("/resources)
        public class MyResource {
 
        @GET
        @Path("{var:.*}/stuff")
        public String get() {...}
        }
```

 

 

下面的GET方法将路由到getResource()方法：

```
GET /resources/stuff
GET /resources/foo/stuff
GET /resources/on/and/on/stuff
```

 

表达式的格式是：

```
"{" variable-name [ ":" regular-expression ] "}"
```

```
 
```

正则表达式部分是可选的。当表达式不提供时，它默认为一个通配符匹配特定的部分。在正则表达式条件下，这个表达式默认为是：

 

```
"([]*)"
```

 

 

示例：

@Path("/resources/{var}/stuff")

将匹配它们：

 

```
GET /resources/foo/stuff 
GET /resources/bar/stuff
```

 

 

但是不能匹配：

```
GET /resources/a/bunch/of/stuff
```