Close

JAX-RS - Using Multiple URI Template Variables

[Last Updated: Feb 9, 2016]

A URI path template can have one or more variables, with each variable name surrounded by curly brackets. Any one of them can have regular expressions as well.


Example

In this example we are going to show how to handle this kind of service requests: http://example.com/api/orders/453/items/s34

Rewriting above request to capture variable parts http://example.com/api/orders/{orderId}/items/{itemId}

Assuming our orderId can have digits only and there can be any number of digits (at least one digit is required). Item id starts with an alphabet followed by two digits:
http://example.com/api/orders/{orderId:\\d+}/items/{itemId:[a-z]\\d{2,3}}


We are going to create two java methods, one with regex and one without any regex to show how we can response back in case of invalid order id or item id instead of showing unfriendly 404 (Not Found) error.


Please run the tests or use this uri from your browser:
http://localhost:8080/rest-multiple-uri-variables/api/orders/3454/items/a33


Example Project

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

Multiple Uri Variables With Regex Select All Download
  • rest-multiple-uri-variables
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • OrderService.java
        • test
          • java
            • com
              • logicbig
                • example

    See Also