I am looking for a way to have complex URL mappings that would depend on the content of the database. For instance I show two URL mappings:
/{category}/
/{category}/{slug}/{id}
Categories can be for instance:
apples, pears, lemons -> resolve to FruitListController,
beans, onions, potatoes -> resolve to VegetableListController.
- Note that those categories are stored in database and might be changed.
If I have in addition the slug and id, both of them must be checked against the database if they exist.
Can I somehow write some kind “Category handler”, which would return the corresponding Category and associated Controller?
Obviously this is a problem of translating URL -> Request. Also, is there a way to generate backwards Request -> URL in similar way? I would like something like in templates:
<c:foreach="apples as apple"
<a href="${link AppleController:defaultView, ID = apple.id}">${apple.name}</a>
</c:foreach>
Use WebArgumentResolvers. They have access to the WebRequest to see your URL. The resolvers can do your database lookups. The FruitWebArgumentResolver could return a Fruit or return UNRESOLVED. The VegetableArgumentResolver could return a Vegetable or return UNRESOLVED. After the argument is resolved, the handler adapter can map to the RequestMapping that takes the specific type as an argument. For example,
To see an example of this, I have a blog post here that uses the same type of mechanism:
http://www.adamweigold.com/2012/01/using-multpartrequestresolvers-with.html