springspring-mvcurl-mapping

Spring MVC 3 - optional URL parameter


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?

/


Solution

  • 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);
        }    
    }