Vojtěch
Vojtěch

Reputation: 12416

Spring MVC: Advanced annotation based mapping

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.

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>

Upvotes: 1

Views: 1215

Answers (1)

aweigold
aweigold

Reputation: 6879

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,

@RequestMapping("/{catagory}/{slug}")
public void fruitSlugList(Fruit fruit, @PathVariable("slug") String slug){

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

Upvotes: 2

Related Questions