user3706481
user3706481

Reputation: 61

How to get path parameters from path using Java

I have a path /departments/{dept}/employees/{id}. How do I obtain dept and id from path /departments/{dept}/employees/{id}?

For example, I would like to obtain dept1 and id1 if path is /departments/dept1/employees/id1

I tried

String pattern1 = "departments/"
String pattern2 = "/employees"
Pattern p = Pattern.compile(Pattern.quote(pattern1) + "(.*?)" + Pattern.quote(pattern2));
Matcher m = p.matcher(text);
while (m.find()) {
   String a = m.group(1);
}

Is there a simpler way to obtain dept1 and id1? I would prefer not using string.split as I have different paths for which I want to obtain path parameters and I prefer not having a dependency on the index position of the path parameters.

Upvotes: 1

Views: 3539

Answers (3)

Federico Piazza
Federico Piazza

Reputation: 31045

If you are using Spring framework, then you can use a class specifically for this purpose named AntPathMatcher and use its method extractUriTemplateVariables

So, you can have the following:

AntPathMatcher matcher = new AntPathMatcher();

String url = "/departments/dept1/employees/id1";
String pattern = "/departments/{dept}/employees/{id}";

System.out.println(matcher.match(pattern, url));
System.out.println(matcher.extractUriTemplateVariables(pattern, url).get("dept"));
System.out.println(matcher.extractUriTemplateVariables(pattern, url).get("id"));

Upvotes: 4

Yury Finchenko
Yury Finchenko

Reputation: 1075

If you prefer regix:

import org.junit.Test;
import java.util.regex.Pattern;

        public class ExampleUnitTest {

        @Test
        public void test_method() throws Exception {

            Pattern digital_group = Pattern.compile("[//]");

            CharSequence line = "test/message/one/thing";

            String[] re = digital_group.split(line);

            for (int i=0;i<re.length;i++) {

                System.out.println(re[i]);

            }

        } 

    } //END: class ExampleUnitTest

The output is:

test
message
one
thing

Process finished with exit code 0

Upvotes: 0

user7332139
user7332139

Reputation:

Using Spring... or:

String url = /departments/{dept}/employees/{id}
             /----none--/-dept-/---none---/-id-

Make a split of url and get the position of array 1 and 3:

String urlSplited = url.split("/");
String dept = urlSplited[1];
String id = urlSplited[3];

Upvotes: 1

Related Questions