Spring MVC 3 - optional URL parameter

Adrian Adamczyk picture Adrian Adamczyk · Sep 10, 2012 · Viewed 15.9k times · Source

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?

/

Answer

Santiago picture Santiago · Jan 25, 2013

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.