Twitter

vineri, 2 octombrie 2015

JAX-RS working with URI path templates example

In this post, you can see a very simple JAX-RS application for working with URI path templates

URI path templates are URIs with variables embedded within the URI syntax. In the JAX-RS HelloWorld Example, we have used a static (hard-coded) relative URI, helloworld (or, /helloworld). In order to use a path template  just wrap the variables in curly braces, as below (/users is the static part of the relative URI, while username is the variable part):
@Path("/users/{username}")
If we suppose that our application (JaxrsURIpathtemplates_EE7) has the base URI, webresource, and the above URI path template then URL like below will work:

http://localhost:8080/JaxrsURIpathtemplates_EE7/webresources/users/leo
http://localhost:8080/JaxrsURIpathtemplates_EE7/webresources/users/12345
http://localhost:8080/JaxrsURIpathtemplates_EE7/webresources/users/!@!

The {username} was replaced by, leo, 12345 and !@!.  If leo looks like an user name, we cannot say the same thing about 12345 and !@!. In order to restrict the variable to a pattern, it is possible to declare a particular regular expression, which overrides the default regular expression, [^/]+, for example:
@Path("/users/{username: [a-zA-Z][a-zA-Z_0-9]*}")
The variables can be chained. This is ok:
@Path("/users/{username: [a-zA-Z][a-zA-Z_0-9]*}/admin/{id: \\d+}")
A possible URL will be:

http://localhost:8080/JaxrsURIpathtemplates_EE7/webresources/users/leo/admin/9009

We also can chain variables as below (see, JAX-RS working with @Path at class and method level):
import javax.ws.rs.Produces;
import javax.ws.rs.GET;
import javax.ws.rs.Path;

@Path("/users/{username: [a-zA-Z][a-zA-Z_0-9]*}")
public class HelloUsersResource {

 @GET
 @Path("/admin/{id: \\d+}")
 @Produces("text/plain")
 public String helloAdmin() {
  return "Hello, Admin!";
 }
   
 @GET
 @Path("/user")
 @Produces("text/plain")
 public String helloUser() {
  return "Hello, User!";
 }
}
Some valid URL are:

// for admins
http://localhost:8080/JaxrsURIpathtemplates_EE7/webresources/users/leo/admin/9001

// for normal users
http://localhost:8080/JaxrsURIpathtemplates_EE7/webresources/users/kelly/user

The complete application is available here.

In the below figure (copy-paste from Java EE 7 tutorial) you can see more examples:

These variables are substituted at runtime in order for a resource to respond to a request based on the substituted URI. Commonly they are provided by the user (or indirectly computed via the user actions). In the next post, you will see how to obtain the variables passed by the user from an interface.

Niciun comentariu:

Trimiteți un comentariu