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):
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:


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:


We also can chain variables as below (see, JAX-RS working with @Path at class and method level):

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

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

// for admins

// for normal users

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