Close

JAX-RS - Using Regex in @Path URI template variable

[Last Updated: Jun 13, 2017]

The @Path template variable is not limited to a fixed string expression, we can also use regular expressions for them. The regex must be a valid expression per Java regex specs.

By default, the URI variable must match the regular expression "[^/]+?". That means a path of one or more characters value will match, also the leading '/' is always ignored, so it's not necessary to always put a leading '/' in path variable names.

A @Path value isn't required to have leading or trailing slashes (/). The JAX-RS runtime parses URI path templates the same way, whether or not they have leading or trailing slashes.

Syntax for using regex

@Path("fixedPart/{variable: regex}")

The following example restrict user name to be only of lowercase and uppercase alphanumeric characters.

@Path("users/{username: [a-zA-Z][a-zA-Z_0-9]*}")
If request doesn't match the template, a 404 (Not Found) response will be sent to the client.


Example Project:

In the following example we have created two methods with regex expression for @Path template variables. One method accept orderId only having digits of length from 3 to 5 (\\d{3,5})and other method going to accept an alphabet followed by digits of length 2 to 3 ([a-z]\\d{2,3}).

Following URIs are valid

http://localhost:8080/rest-uri-path-regex/api/orders/333
http://localhost:8080/rest-uri-path-regex/api/orders/s36

There are also some unit tests validating the URIs.

Steps to create the project are same as previous tutorials.

Dependencies and Technologies Used:

  • jersey-core-server 2.22.1: Jersey core server implementation.
  • jersey-container-servlet 2.22.1: Jersey core Servlet 3.x implementation.
  • jersey-test-framework-provider-jdk-http 2.22.1: Jersey Test Framework - JDK HTTP container.
  • JDK 1.8
  • Maven 3.0.4

Regex In Path Example Select All Download
  • rest-uri-path-regex
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • OrderService.java
        • test
          • java
            • com
              • logicbig
                • example

    See Also