0
# Path Template Matching
1
2
Fast path template matching system for REST API routing with parameter extraction. Optimized for high-performance microservices with stem-based matching algorithms that provide efficient path resolution and parameter binding for HTTP request routing.
3
4
## Capabilities
5
6
### Path Template Matcher
7
8
Generic path template matcher that provides fast routing and parameter extraction for REST APIs.
9
10
```java { .api }
11
/**
12
* Fast path matching utility for path templates with stem-based optimization
13
*/
14
public class PathTemplateMatcher<T> {
15
// Constructor (default - no explicit public constructors)
16
17
// Template management
18
public PathTemplateMatcher<T> add(PathTemplate template, T value);
19
public PathTemplateMatcher<T> add(String pathTemplate, T value);
20
public PathTemplateMatcher<T> addAll(PathTemplateMatcher<T> pathTemplateMatcher);
21
public PathTemplateMatcher<T> remove(String pathTemplate);
22
23
// Matching operations
24
public PathMatchResult<T> match(String path);
25
public T get(String template);
26
public Set<PathTemplate> getPathTemplates();
27
}
28
29
/**
30
* Result of path template matching with associated value
31
*/
32
public interface PathMatchResult<T> extends PathTemplateMatch {
33
T getValue();
34
}
35
```
36
37
**Usage Examples:**
38
39
```java
40
import com.networknt.utility.PathTemplateMatcher;
41
import com.networknt.utility.PathTemplate;
42
43
// Create matcher for API endpoints
44
PathTemplateMatcher<String> apiMatcher = new PathTemplateMatcher<>();
45
46
// Add route patterns with associated handlers
47
apiMatcher.add("/api/users/{id}", "getUserById");
48
apiMatcher.add("/api/users", "getUsers");
49
apiMatcher.add("/api/users/{id}/posts/{postId}", "getUserPost");
50
apiMatcher.add("/api/orders/{orderId}/items", "getOrderItems");
51
52
// Match incoming requests
53
PathMatchResult<String> result = apiMatcher.match("/api/users/123");
54
if (result != null) {
55
String handlerName = result.getValue(); // "getUserById"
56
Map<String, String> params = result.getParameters(); // {id=123}
57
String template = result.getMatchedTemplate(); // "/api/users/{id}"
58
}
59
60
// Complex path matching
61
PathMatchResult<String> complexResult = apiMatcher.match("/api/users/456/posts/789");
62
if (complexResult != null) {
63
String handler = complexResult.getValue(); // "getUserPost"
64
Map<String, String> params = complexResult.getParameters();
65
// {id=456, postId=789}
66
}
67
68
// Check registered templates
69
Set<PathTemplate> templates = apiMatcher.getPathTemplates();
70
for (PathTemplate template : templates) {
71
System.out.println("Registered: " + template.getTemplateString());
72
}
73
```
74
75
### Path Template
76
77
Individual path template representation with parameter parsing and matching capabilities.
78
79
```java { .api }
80
/**
81
* Represents a parsed web socket path template with parameter support
82
*/
83
public class PathTemplate implements Comparable<PathTemplate> {
84
// Factory method
85
public static PathTemplate create(String inputPath);
86
87
// Matching operations
88
public boolean matches(String path, Map<String, String> pathParameters);
89
90
// Template information
91
public String getBase();
92
public String getTemplateString();
93
public Set<String> getParameterNames();
94
95
// Comparison for priority ordering
96
public int compareTo(PathTemplate other);
97
}
98
```
99
100
**Usage Examples:**
101
102
```java
103
import com.networknt.utility.PathTemplate;
104
import java.util.HashMap;
105
import java.util.Map;
106
107
// Create path templates
108
PathTemplate userTemplate = PathTemplate.create("/api/users/{id}");
109
PathTemplate postTemplate = PathTemplate.create("/api/users/{userId}/posts/{postId}");
110
111
// Get template information
112
String templateString = userTemplate.getTemplateString(); // "/api/users/{id}"
113
String base = userTemplate.getBase(); // "/api/users/"
114
Set<String> params = userTemplate.getParameterNames(); // ["id"]
115
116
// Match paths and extract parameters
117
Map<String, String> pathParams = new HashMap<>();
118
boolean matches = userTemplate.matches("/api/users/123", pathParams);
119
// matches = true, pathParams = {id=123}
120
121
// Complex template matching
122
Map<String, String> complexParams = new HashMap<>();
123
boolean complexMatches = postTemplate.matches("/api/users/456/posts/789", complexParams);
124
// complexMatches = true, complexParams = {userId=456, postId=789}
125
126
// Template comparison (for priority ordering)
127
List<PathTemplate> templates = Arrays.asList(
128
PathTemplate.create("/api/users"),
129
PathTemplate.create("/api/users/{id}"),
130
PathTemplate.create("/api/users/{id}/posts/{postId}")
131
);
132
Collections.sort(templates); // Sorts by specificity
133
```
134
135
### Path Template Match
136
137
Result container for path template matches containing the matched template and extracted parameters.
138
139
```java { .api }
140
/**
141
* Result container for path template matches
142
*/
143
public class PathTemplateMatch {
144
// Constructor
145
public PathTemplateMatch(String matchedTemplate, Map<String, String> parameters);
146
147
// Accessors
148
public String getMatchedTemplate();
149
public Map<String, String> getParameters();
150
}
151
```
152
153
**Usage Examples:**
154
155
```java
156
import com.networknt.utility.PathTemplateMatch;
157
import java.util.Map;
158
159
// Create match result
160
Map<String, String> params = Map.of("id", "123", "action", "edit");
161
PathTemplateMatch match = new PathTemplateMatch("/api/users/{id}/{action}", params);
162
163
// Access match information
164
String template = match.getMatchedTemplate(); // "/api/users/{id}/{action}"
165
Map<String, String> extractedParams = match.getParameters(); // {id=123, action=edit}
166
167
// Use in request processing
168
public void handleRequest(PathTemplateMatch match) {
169
String template = match.getMatchedTemplate();
170
Map<String, String> params = match.getParameters();
171
172
switch (template) {
173
case "/api/users/{id}":
174
handleUserRequest(params.get("id"));
175
break;
176
case "/api/users/{id}/posts/{postId}":
177
handleUserPostRequest(params.get("id"), params.get("postId"));
178
break;
179
}
180
}
181
```
182
183
### Advanced Usage Patterns
184
185
**REST API Router Implementation:**
186
```java
187
public class ApiRouter {
188
private final PathTemplateMatcher<RequestHandler> handlers = new PathTemplateMatcher<>();
189
190
public void addRoute(String template, RequestHandler handler) {
191
handlers.add(template, handler);
192
}
193
194
public void handleRequest(String path, HttpRequest request, HttpResponse response) {
195
PathMatchResult<RequestHandler> result = handlers.match(path);
196
if (result != null) {
197
RequestHandler handler = result.getValue();
198
Map<String, String> pathParams = result.getParameters();
199
handler.handle(request, response, pathParams);
200
} else {
201
response.setStatus(404);
202
}
203
}
204
}
205
206
// Usage
207
ApiRouter router = new ApiRouter();
208
router.addRoute("/api/users/{id}", new UserHandler());
209
router.addRoute("/api/orders/{orderId}/items", new OrderItemsHandler());
210
router.handleRequest("/api/users/123", request, response);
211
```
212
213
**WebSocket Path Matching:**
214
```java
215
public class WebSocketPathMatcher {
216
private final PathTemplateMatcher<WebSocketHandler> wsHandlers = new PathTemplateMatcher<>();
217
218
public void addWebSocketHandler(String pathTemplate, WebSocketHandler handler) {
219
wsHandlers.add(pathTemplate, handler);
220
}
221
222
public WebSocketHandler findHandler(String wsPath) {
223
PathMatchResult<WebSocketHandler> result = wsHandlers.match(wsPath);
224
return result != null ? result.getValue() : null;
225
}
226
227
public Map<String, String> extractPathParameters(String wsPath) {
228
PathMatchResult<WebSocketHandler> result = wsHandlers.match(wsPath);
229
return result != null ? result.getParameters() : Collections.emptyMap();
230
}
231
}
232
```
233
234
**Multi-Version API Support:**
235
```java
236
PathTemplateMatcher<ApiHandler> versionedMatcher = new PathTemplateMatcher<>();
237
238
// Add versioned endpoints
239
versionedMatcher.add("/v1/api/users/{id}", new V1UserHandler());
240
versionedMatcher.add("/v2/api/users/{id}", new V2UserHandler());
241
versionedMatcher.add("/api/users/{id}", new LatestUserHandler()); // Default to latest
242
243
// Route based on version
244
PathMatchResult<ApiHandler> result = versionedMatcher.match(requestPath);
245
if (result != null) {
246
ApiHandler handler = result.getValue();
247
handler.processRequest(result.getParameters());
248
}
249
```
250
251
**Performance Optimization:**
252
```java
253
// Pre-compile templates for better performance
254
public class OptimizedRouter {
255
private final PathTemplateMatcher<String> matcher;
256
257
public OptimizedRouter(Map<String, String> routes) {
258
matcher = new PathTemplateMatcher<>();
259
260
// Add all routes at once for optimal internal structure
261
for (Map.Entry<String, String> route : routes.entrySet()) {
262
matcher.add(route.getKey(), route.getValue());
263
}
264
}
265
266
public String route(String path) {
267
PathMatchResult<String> result = matcher.match(path);
268
return result != null ? result.getValue() : null;
269
}
270
}
271
```