Skip to content

Commit 4e339ed

Browse files
committed
add reverse routing by route name
1 parent ece00fa commit 4e339ed

File tree

1 file changed

+34
-1
lines changed

1 file changed

+34
-1
lines changed

_posts/2015-03-17-reverse-routing.md

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,40 @@ parameters.put("action", "new");
4444
String url = routeContext.uriFor("/contacts/{id}", parameters);
4545
```
4646

47-
By default (via `DefaultRouter`) the `uriFor` method automatically encode the parameters values.
47+
Are some scenarios when it's more ease to use the route name for `uriFor()`.
48+
In few words I can add a route (in an hypothetical blog application) that render a template with:
49+
50+
```java
51+
GET("/blogs/{year}/{month}/{day}/{title}", (routeContext) -> { routeContext.render("myTemplate")});
52+
```
53+
54+
It's hard to create the reverse routing using the `uriPattern`:
55+
56+
```java
57+
Map<String, Object> parameters = ...
58+
routeContext.uriFor("/blogs/{year}/{month}/{day}/{title}", parameters);
59+
```
60+
61+
The simplest solution is to add a `name` to our route and to use this name when we build the URL(reverse routing) to that route:
62+
63+
```java
64+
GET("/blogs/{year}/{month}/{day}/{title}", (routeContext) -> { routeContext.render("myTemplate")}).named("blog");
65+
```
66+
67+
The new code becomes more short and readable:
68+
69+
```java
70+
Map<String, Object> parameters = ...
71+
routeContext.uriFor("blog", parameters);
72+
```
73+
74+
Advantages:
75+
76+
- it is often more descriptive than hard-coding the `uriPattern`
77+
- it allows you to change `uriPattern` in one go, without having to remember to change URLs all over the place.
78+
79+
80+
**Note:** By default (via `DefaultRouter`) the `uriFor` method automatically encode the parameters values.
4881

4982
In conclusion if you want to create links to routes or controllers you must use `Router.uriFor` methods.
5083

0 commit comments

Comments
 (0)