Announcement Announcement Module
Collapse
No announcement yet.
Multiple converters for the same class Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Multiple converters for the same class

    Hi,

    I'm using a Converter from String to Product which I can use to automatically load products from database using a name and receive them in my controller methods:

    Code:
    @RequestMapping("/product/{name}")
    public void viewProduct(@PathVariable("name") Product product) {
       ...
    }
    Now, I've got a form with a select drop-down and I need to bind products from that. But here I can't use the product name as before, and I must use the product identifier (an integer) for binding. And although this id is a number, the form will submit a string, so the converter needs to be, again, from String to Product. So I would end up with two Converter<String, Product>, which is a conflict.

    Is there a solution for this? I know I could parse the string inside the converter to see if it's a name or a number, but I feel this is not a good approach.

    Thanks in advance.

  • #2
    Assuming you use Spring 3.1 the path variable can also contain a regular expression, that way you could create 2 mappings one with a String and one with a numeric type (Long probably) and based on that have 2 converters (Long, Product and String, Product).

    Comment


    • #3
      Marten: thanks for your reply.

      I'm using Spring 3.1, but I think it won't be possible for me to create a second @PathVariable mapping using a numeric type, because the product number I'm trying to bind is not part of the URL in the second case: it's a form property submitted using POST.

      Comment


      • #4
        Which makes it even easier... Then you don't need to do nasty things with regular expressions.

        Comment


        • #5
          Originally posted by Marten Deinum View Post
          Which makes it even easier... Then you don't need to do nasty things with regular expressions.
          Then I must really have missed the point I'll try to explain my question a little better:

          Here's my form:

          Code:
          class Checkout {
          
            Product product;
            ...
          }
          and this my html:

          Code:
          <form:select path="product">
            <form:option label="Product 123" value="123"/>
            ...
          </form:select>
          so... how can I tell Spring which one of my two (String, Product) converters it should use to bind "123" to a Product?

          Comment

          Working...
          X