JBoss Resteasy 2之URL匹配

  在上一篇helloworld中,简单介绍了入门,本文讲解其URL匹配,也是REST
中很重要的一环
看例子:

@Path("/users")
public class UserRestService {
 
	@GET
	@Path("{name}")
	public Response getUserByName(@PathParam("name") String name) {
 
		return Response.status(200)
			.entity("getUserByName is called, name : " + name).build();
 
	}
	@GET
	@Path("{id : \\d+}") //support digit only
	public Response getUserById(@PathParam("id") String id) {
 
	   return Response.status(200).entity("getUserById is called, id : " + id).build();
 
	}
 
	@GET
	@Path("/username/{username : [a-zA-Z][a-zA-Z_0-9]}")
	public Response getUserByUserName(@PathParam("username") String username) {
 
	   return Response.status(200)
		.entity("getUserByUserName is called, username : " + username).build();
 
	}
 
	@GET
	@Path("/books/{isbn : \\d+}")
	public Response getUserBookByISBN(@PathParam("isbn") String isbn) {
 
	   return Response.status(200)
		.entity("getUserBookByISBN is called, isbn : " + isbn).build();
 
	}
 

可以看到,还支持正则表达式。所以,容易看出:

1) “/users/999”
返回:getUserById is called, id : 999

2) /users/username/aaa”
  不匹配

3) users/books/999”
  返回:getUserBookByISBN is called, isbn : 999

再看例子:
 
@Path("/users")
public class UserRestService {
 
	@GET
	@Path("{id}")
	public Response getUserById(@PathParam("id") String id) {
 
	   return Response.status(200).entity("getUserById is called, id : " + id).build();
 
	}
 


则“/users/22667788 匹配
  getUserById is called, id : 22667788

多个参数传入的例子:
 
@Path("/users")
public class UserRestService {
 
	@GET
	@Path("{year}/{month}/{day}")
	public Response getUserHistory(
			@PathParam("year") int year,
			@PathParam("month") int month, 
			@PathParam("day") int day) {
 
	   String date = year + "/" + month + "/" + day;
 
	   return Response.status(200)
		.entity("getUserHistory is called, year/month/day : " + date)
		.build();
 
	}
 


则:
“/users/2011/06/30”
输出:
   getUserHistory is called, year/month/day : 2011/6/30

你可能感兴趣的:(java,REST)