0
# HTTP Routing
1
2
HTTP-specific routing system with method-based handlers, filters, and comprehensive request/response processing. Supports RESTful APIs, middleware, and error handling.
3
4
## Capabilities
5
6
### HttpRouting Interface
7
8
The main HTTP routing interface that handles HTTP requests across all HTTP versions.
9
10
```java { .api }
11
/**
12
* HTTP routing. This routing is capable of handling any HTTP version.
13
*/
14
interface HttpRouting extends Routing, Prototype.Api {
15
/**
16
* Creates new instance of HttpRouting builder.
17
* @return a new instance
18
*/
19
static Builder builder();
20
21
/**
22
* Create a default router.
23
* @return new default router
24
*/
25
static HttpRouting create();
26
27
/**
28
* Empty routing (all requests will return 404).
29
* @return empty routing
30
*/
31
static HttpRouting empty();
32
33
/**
34
* Route a request.
35
* @param ctx the underlying connection context
36
* @param request the request to route
37
* @param response the response for the request
38
*/
39
void route(ConnectionContext ctx, RoutingRequest request, RoutingResponse response);
40
41
/**
42
* Security associated with this routing.
43
* @return security
44
*/
45
HttpSecurity security();
46
47
@Override
48
default Class<? extends Routing> routingType() {
49
return HttpRouting.class;
50
}
51
}
52
```
53
54
**Usage Examples:**
55
56
```java
57
import io.helidon.webserver.http.HttpRouting;
58
import io.helidon.http.Method;
59
60
// Create simple routing
61
HttpRouting routing = HttpRouting.builder()
62
.get("/hello", (req, res) -> res.send("Hello World!"))
63
.post("/users", (req, res) -> {
64
// Handle user creation
65
res.status(201).send("User created");
66
})
67
.build();
68
69
// Create default routing (returns "Helidon WebServer works!")
70
HttpRouting defaultRouting = HttpRouting.create();
71
72
// Create empty routing (returns 404 for all requests)
73
HttpRouting emptyRouting = HttpRouting.empty();
74
```
75
76
### HttpRouting Builder
77
78
Fluent API builder for creating HTTP routing with comprehensive configuration options.
79
80
```java { .api }
81
/**
82
* Fluent API builder for HttpRouting.
83
*/
84
interface HttpRouting.Builder extends HttpRules, io.helidon.common.Builder<Builder, HttpRouting> {
85
/**
86
* Register HTTP services.
87
* @param service services to register
88
* @return updated builder
89
*/
90
Builder register(HttpService... service);
91
92
/**
93
* Register HTTP services with path prefix.
94
* @param path path prefix for services
95
* @param service services to register
96
* @return updated builder
97
*/
98
Builder register(String path, HttpService... service);
99
100
/**
101
* Add HTTP route.
102
* @param route route to add
103
* @return updated builder
104
*/
105
Builder route(HttpRoute route);
106
107
/**
108
* Add HTTP route with supplier.
109
* @param route route supplier
110
* @return updated builder
111
*/
112
default Builder route(Supplier<? extends HttpRoute> route);
113
114
/**
115
* Add route for specific method and path.
116
* @param method HTTP method
117
* @param pathPattern path pattern
118
* @param handler request handler
119
* @return updated builder
120
*/
121
default Builder route(Method method, String pathPattern, Handler handler);
122
123
/**
124
* Add route for specific method and path matcher.
125
* @param method HTTP method
126
* @param pathMatcher path matcher
127
* @param handler request handler
128
* @return updated builder
129
*/
130
default Builder route(Method method, PathMatcher pathMatcher, Handler handler);
131
132
/**
133
* Add route with method predicate.
134
* @param methodPredicate method predicate
135
* @param pathMatcher path matcher
136
* @param handler request handler
137
* @return updated builder
138
*/
139
default Builder route(Predicate<Method> methodPredicate, PathMatcher pathMatcher, Handler handler);
140
141
/**
142
* Add route for specific method without path restriction.
143
* @param method HTTP method
144
* @param handler request handler
145
* @return updated builder
146
*/
147
default Builder route(Method method, Handler handler);
148
}
149
```
150
151
### HTTP Method Shortcuts
152
153
Convenient methods for common HTTP verbs.
154
155
```java { .api }
156
/**
157
* HTTP method shortcut methods in HttpRouting.Builder
158
*/
159
interface Builder {
160
/**
161
* Add GET route with path pattern.
162
* @param pathPattern path pattern
163
* @param handlers request handlers
164
* @return updated builder
165
*/
166
default Builder get(String pathPattern, Handler... handlers);
167
168
/**
169
* Add GET route without path restriction.
170
* @param handlers request handlers
171
* @return updated builder
172
*/
173
default Builder get(Handler... handlers);
174
175
/**
176
* Add POST route with path pattern.
177
* @param pathPattern path pattern
178
* @param handlers request handlers
179
* @return updated builder
180
*/
181
default Builder post(String pathPattern, Handler... handlers);
182
183
/**
184
* Add POST route without path restriction.
185
* @param handlers request handlers
186
* @return updated builder
187
*/
188
default Builder post(Handler... handlers);
189
190
/**
191
* Add PUT route with path pattern.
192
* @param pathPattern path pattern
193
* @param handlers request handlers
194
* @return updated builder
195
*/
196
default Builder put(String pathPattern, Handler... handlers);
197
198
/**
199
* Add PUT route without path restriction.
200
* @param handlers request handlers
201
* @return updated builder
202
*/
203
default Builder put(Handler... handlers);
204
205
/**
206
* Add DELETE route with path pattern.
207
* @param pathPattern path pattern
208
* @param handlers request handlers
209
* @return updated builder
210
*/
211
default Builder delete(String pathPattern, Handler... handlers);
212
213
/**
214
* Add DELETE route without path restriction.
215
* @param handlers request handlers
216
* @return updated builder
217
*/
218
default Builder delete(Handler... handlers);
219
220
/**
221
* Add HEAD route with path pattern.
222
* @param pathPattern path pattern
223
* @param handlers request handlers
224
* @return updated builder
225
*/
226
default Builder head(String pathPattern, Handler... handlers);
227
228
/**
229
* Add HEAD route without path restriction.
230
* @param handlers request handlers
231
* @return updated builder
232
*/
233
default Builder head(Handler... handlers);
234
235
/**
236
* Add OPTIONS route with path pattern.
237
* @param pathPattern path pattern
238
* @param handlers request handlers
239
* @return updated builder
240
*/
241
default Builder options(String pathPattern, Handler... handlers);
242
243
/**
244
* Add OPTIONS route without path restriction.
245
* @param handlers request handlers
246
* @return updated builder
247
*/
248
default Builder options(Handler... handlers);
249
250
/**
251
* Add TRACE route with path pattern.
252
* @param pathPattern path pattern
253
* @param handlers request handlers
254
* @return updated builder
255
*/
256
default Builder trace(String pathPattern, Handler... handlers);
257
258
/**
259
* Add TRACE route without path restriction.
260
* @param handlers request handlers
261
* @return updated builder
262
*/
263
default Builder trace(Handler... handlers);
264
265
/**
266
* Add PATCH route with path pattern.
267
* @param pathPattern path pattern
268
* @param handlers request handlers
269
* @return updated builder
270
*/
271
default Builder patch(String pathPattern, Handler... handlers);
272
273
/**
274
* Add PATCH route without path restriction.
275
* @param handlers request handlers
276
* @return updated builder
277
*/
278
default Builder patch(Handler... handlers);
279
280
/**
281
* Add route for any HTTP method with path pattern.
282
* @param pathPattern path pattern
283
* @param handlers request handlers
284
* @return updated builder
285
*/
286
default Builder any(String pathPattern, Handler... handlers);
287
288
/**
289
* Add route for any HTTP method without path restriction.
290
* @param handlers request handlers
291
* @return updated builder
292
*/
293
default Builder any(Handler... handlers);
294
}
295
```
296
297
**Usage Examples:**
298
299
```java
300
import io.helidon.webserver.http.HttpRouting;
301
import io.helidon.http.Method;
302
303
HttpRouting routing = HttpRouting.builder()
304
// Basic HTTP method routes
305
.get("/users", (req, res) -> res.send("Get all users"))
306
.get("/users/{id}", (req, res) -> {
307
String id = req.path().pathParameters().get("id");
308
res.send("Get user: " + id);
309
})
310
.post("/users", (req, res) -> {
311
// Create user logic
312
res.status(201).send("User created");
313
})
314
.put("/users/{id}", (req, res) -> {
315
String id = req.path().pathParameters().get("id");
316
res.send("Updated user: " + id);
317
})
318
.delete("/users/{id}", (req, res) -> {
319
String id = req.path().pathParameters().get("id");
320
res.status(204).send();
321
})
322
323
// Advanced routing patterns
324
.route(Method.GET, "/admin/*", (req, res) -> {
325
// Admin routes
326
})
327
.any("/health", (req, res) -> res.send("OK"))
328
329
.build();
330
```
331
332
### Filter and Feature Management
333
334
Advanced routing configuration with filters, features, and error handling.
335
336
```java { .api }
337
/**
338
* Filter and feature methods in HttpRouting.Builder
339
*/
340
interface Builder {
341
/**
342
* Add a new filter.
343
* @param filter filter to add
344
* @return updated builder
345
*/
346
Builder addFilter(Filter filter);
347
348
/**
349
* Add a new feature.
350
* @param feature feature to add
351
* @return updated builder
352
*/
353
default Builder addFeature(HttpFeature feature);
354
355
/**
356
* Add a new feature with supplier.
357
* @param feature feature supplier
358
* @return updated builder
359
*/
360
Builder addFeature(Supplier<? extends HttpFeature> feature);
361
362
/**
363
* Register error handler for specific exception type.
364
* @param exceptionClass the type of exception to handle
365
* @param handler the error handler
366
* @param <T> exception type
367
* @return updated builder
368
*/
369
<T extends Throwable> Builder error(Class<T> exceptionClass, ErrorHandler<? super T> handler);
370
371
/**
372
* Maximal number of allowed re-routes within routing.
373
* @param maxReRouteCount maximum number of allowed reroutes
374
* @return updated builder
375
*/
376
Builder maxReRouteCount(int maxReRouteCount);
377
378
/**
379
* Configure security for this routing.
380
* @param security security to use
381
* @return updated builder
382
*/
383
Builder security(HttpSecurity security);
384
385
/**
386
* Create a copy of this builder.
387
* @return builder that is a copy of this builder
388
*/
389
Builder copy();
390
}
391
```
392
393
**Usage Examples:**
394
395
```java
396
import io.helidon.webserver.http.*;
397
398
// Custom filter implementation
399
Filter loggingFilter = (chain, req, res) -> {
400
System.out.println("Request: " + req.method() + " " + req.path());
401
chain.proceed();
402
};
403
404
// Custom feature implementation
405
HttpFeature corsFeature = routing -> {
406
routing.addFilter((chain, req, res) -> {
407
res.header("Access-Control-Allow-Origin", "*");
408
chain.proceed();
409
});
410
};
411
412
// Error handler
413
ErrorHandler<IllegalArgumentException> argErrorHandler =
414
(req, res, ex) -> res.status(400).send("Bad request: " + ex.getMessage());
415
416
HttpRouting routing = HttpRouting.builder()
417
// Add filters
418
.addFilter(loggingFilter)
419
420
// Add features
421
.addFeature(corsFeature)
422
423
// Add error handlers
424
.error(IllegalArgumentException.class, argErrorHandler)
425
.error(RuntimeException.class, (req, res, ex) ->
426
res.status(500).send("Internal error"))
427
428
// Configure security
429
.security(HttpSecurity.create())
430
431
// Set max re-route count
432
.maxReRouteCount(5)
433
434
// Regular routes
435
.get("/api/data", (req, res) -> {
436
if (req.query().get("invalid").isPresent()) {
437
throw new IllegalArgumentException("Invalid parameter");
438
}
439
res.send("Data response");
440
})
441
442
.build();
443
```
444
445
### HttpRules Interface
446
447
Base interface for HTTP routing rule configuration.
448
449
```java { .api }
450
/**
451
* Interface for defining HTTP routing rules.
452
*/
453
interface HttpRules {
454
/**
455
* Register HTTP services.
456
* @param service services to register
457
* @return updated rules
458
*/
459
HttpRules register(HttpService... service);
460
461
/**
462
* Register HTTP services with supplier.
463
* @param service service supplier
464
* @return updated rules
465
*/
466
default HttpRules register(Supplier<? extends HttpService> service);
467
468
/**
469
* Register HTTP services with path prefix.
470
* @param pathPattern path prefix
471
* @param service services to register
472
* @return updated rules
473
*/
474
HttpRules register(String pathPattern, HttpService... service);
475
476
/**
477
* Add HTTP route.
478
* @param route route to add
479
* @return updated rules
480
*/
481
HttpRules route(HttpRoute route);
482
483
/**
484
* Add route with supplier.
485
* @param route route supplier
486
* @return updated rules
487
*/
488
default HttpRules route(Supplier<? extends HttpRoute> route);
489
490
// HTTP method shortcuts
491
default HttpRules get(String pathPattern, Handler... handlers);
492
default HttpRules post(String pathPattern, Handler... handlers);
493
default HttpRules put(String pathPattern, Handler... handlers);
494
default HttpRules delete(String pathPattern, Handler... handlers);
495
default HttpRules head(String pathPattern, Handler... handlers);
496
default HttpRules options(String pathPattern, Handler... handlers);
497
default HttpRules trace(String pathPattern, Handler... handlers);
498
default HttpRules patch(String pathPattern, Handler... handlers);
499
default HttpRules any(String pathPattern, Handler... handlers);
500
}
501
```
502
503
### HttpRoute Interface
504
505
Individual HTTP route definition with method and path configuration.
506
507
```java { .api }
508
/**
509
* HTTP route definition.
510
*/
511
interface HttpRoute {
512
/**
513
* Create route builder.
514
* @return route builder
515
*/
516
static Builder builder();
517
518
/**
519
* Builder for HTTP routes.
520
*/
521
interface Builder extends io.helidon.common.Builder<Builder, HttpRoute> {
522
/**
523
* Set HTTP methods for this route.
524
* @param methods HTTP methods
525
* @return updated builder
526
*/
527
Builder methods(Method... methods);
528
529
/**
530
* Set method predicate for this route.
531
* @param methodPredicate method predicate
532
* @return updated builder
533
*/
534
Builder methods(Predicate<Method> methodPredicate);
535
536
/**
537
* Set path pattern for this route.
538
* @param pathPattern path pattern
539
* @return updated builder
540
*/
541
Builder path(String pathPattern);
542
543
/**
544
* Set path matcher for this route.
545
* @param pathMatcher path matcher
546
* @return updated builder
547
*/
548
Builder path(PathMatcher pathMatcher);
549
550
/**
551
* Set request handler for this route.
552
* @param handler request handler
553
* @return updated builder
554
*/
555
Builder handler(Handler handler);
556
}
557
}
558
```
559
560
**Usage Examples:**
561
562
```java
563
import io.helidon.webserver.http.HttpRoute;
564
import io.helidon.http.Method;
565
566
// Create custom routes
567
HttpRoute getUserRoute = HttpRoute.builder()
568
.methods(Method.GET)
569
.path("/users/{id}")
570
.handler((req, res) -> {
571
String userId = req.path().pathParameters().get("id");
572
res.send("User: " + userId);
573
})
574
.build();
575
576
HttpRoute createUserRoute = HttpRoute.builder()
577
.methods(Method.POST)
578
.path("/users")
579
.handler((req, res) -> {
580
// Handle user creation
581
res.status(201).send("Created");
582
})
583
.build();
584
585
// Use routes in routing
586
HttpRouting routing = HttpRouting.builder()
587
.route(getUserRoute)
588
.route(createUserRoute)
589
.build();
590
```
591
592
## Advanced Routing Patterns
593
594
### Path Parameters and Wildcards
595
596
```java
597
HttpRouting routing = HttpRouting.builder()
598
// Single path parameter
599
.get("/users/{id}", (req, res) -> {
600
String id = req.path().pathParameters().get("id");
601
res.send("User ID: " + id);
602
})
603
604
// Multiple path parameters
605
.get("/users/{userId}/posts/{postId}", (req, res) -> {
606
Map<String, String> params = req.path().pathParameters().toMap();
607
String userId = params.get("userId");
608
String postId = params.get("postId");
609
res.send("User: " + userId + ", Post: " + postId);
610
})
611
612
// Wildcard patterns
613
.get("/static/*", (req, res) -> {
614
String path = req.path().path();
615
// Serve static files
616
})
617
618
// Regex patterns (advanced)
619
.route(Method.GET, PathMatchers.create("/files/{filename:.+}"),
620
(req, res) -> {
621
String filename = req.path().pathParameters().get("filename");
622
// Handle file with any extension
623
})
624
625
.build();
626
```
627
628
### Service Registration with Path Prefixes
629
630
```java
631
// Create a user service
632
HttpService userService = rules -> {
633
rules.get("/", (req, res) -> res.send("All users"))
634
.get("/{id}", (req, res) -> res.send("User details"))
635
.post("/", (req, res) -> res.status(201).send("User created"))
636
.delete("/{id}", (req, res) -> res.status(204).send());
637
};
638
639
// Register with path prefix
640
HttpRouting routing = HttpRouting.builder()
641
.register("/api/users", userService)
642
.register("/admin/users", userService) // Same service, different prefix
643
.build();
644
```
645
646
### Conditional Routing
647
648
```java
649
HttpRouting routing = HttpRouting.builder()
650
// Method-based routing
651
.route(method -> method.equals(Method.GET) || method.equals(Method.HEAD),
652
PathMatchers.exact("/data"),
653
(req, res) -> res.send("GET or HEAD data"))
654
655
// Custom predicates
656
.route(HttpRoute.builder()
657
.methods(Method.GET)
658
.path("/secure/*")
659
.handler((req, res) -> {
660
// Security check
661
if (req.headers().contains("Authorization")) {
662
res.send("Authorized content");
663
} else {
664
res.status(401).send("Unauthorized");
665
}
666
}))
667
668
.build();
669
```
670
671
### Error Handling and Re-routing
672
673
```java
674
HttpRouting routing = HttpRouting.builder()
675
.maxReRouteCount(3) // Prevent infinite re-routing
676
677
.get("/redirect", (req, res) -> {
678
res.reroute("/target"); // Internal redirect
679
})
680
681
.get("/target", (req, res) -> {
682
res.send("Final destination");
683
})
684
685
// Global error handlers
686
.error(IllegalArgumentException.class,
687
(req, res, ex) -> res.status(400).send("Bad request: " + ex.getMessage()))
688
.error(Exception.class,
689
(req, res, ex) -> res.status(500).send("Internal server error"))
690
691
.build();
692
```