Spring MVC 3 - optional URL parameter

15,918

Solution 1

How about this:

@Controller
public class IndexController
{ 
    @RequestMapping("/page{number}")
    public String printIndex(ModelMap model, @PathVariable("number") int number)
    {
        String numberText;

        switch (number)
        {
            case 0:
                numberText = "Zero";
                break;
            case 1:
                numberText = "One";
                break;
            default:
                numberText = "Unknown";
                break;
        }

        model.addAttribute("number", numberText);

        return "page";
    }
    @RequestMapping("/page")
    public String printIndex(ModelMap model)
    {
        return printIndex(model, 1);
    }    
}

Solution 2

You can use something like this:

@RequestParam(value = "name", defaultValue = "") Long name

Keep in mind that you must use the wrappers (like Long) and not the primitives ones (like long).

I hope this will be useful.

Solution 3

you might want to implement a custom WebArgumentResolver and annotation @OptionalPathVariable and handle it yourself

Share:
15,918
Adrian Adamczyk
Author by

Adrian Adamczyk

Updated on June 04, 2022

Comments

  • Adrian Adamczyk
    Adrian Adamczyk almost 2 years

    I've written following code:

    @Controller
    @RequestMapping("/page{number}")
    public class IndexController
    { 
        @RequestMapping(method = RequestMethod.GET)
        public String printIndex(ModelMap model, @PathVariable int number)
        {
            String numberText;
    
            switch (number)
            {
                case 0:
                    numberText = "Zero";
                    break;
                case 1:
                    numberText = "One";
                    break;
                default:
                    numberText = "Unknown";
                    break;
            }
    
            model.addAttribute("number", numberText);
    
            return "page";
        }
    }
    

    And I'm tring to achieve URLs like page1.html, page2.html, page3.html controlled by this method, with one exception: page.html should give same result as page1.html. I'm looking for something to make {number} optional, now it's required.

    Is there a way to do that at I said?

    /

  • Adrian Adamczyk
    Adrian Adamczyk over 11 years
    I had same idea, but I thought that Spring might handle this problem almost itself. I don't know how to explain this, let's say I was expecting something like {number, default=1}.
  • Arjan
    Arjan about 11 years
    But how does this map to a URL parameter? This would require one to use a query parameter such as /page?number=123 rather than a URL path parameter like /page123 as asked about in the question.
  • Kimball Robinson
    Kimball Robinson over 10 years
    Even if technically not the right answer, it was useful to me in my situation. I'm glad it was here.