3

我写了以下代码:

@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";
    }
}

我正在尝试实现由这种方法控制的 page1.html、page2.html、page3.html 等 URL,但有一个例外:page.html 应该给出与 page1.html 相同的结果。我正在寻找使 {number} 可选的东西,现在它是必需的。

我说有没有办法做到这一点?

/

4

4 回答 4

15

你可以使用这样的东西:

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

请记住,您必须使用包装器(如 Long)而不是原始包装器(如 long)。

我希望这会有用。

于 2013-01-25T19:50:25.487 回答
7

这个怎么样:

@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);
    }    
}
于 2012-09-10T20:55:35.950 回答
1

您可能想要实现自定义 WebArgumentResolver 和注释 @OptionalPathVariable 并自己处理

于 2012-09-10T21:08:17.140 回答
0

Rest API - 可选参数和更改值

@GetMapping(value = "/country/list")
public ResponseEntity<?> companyInformationList
(
Pageable pageable,
@RequestParam(name = "q", required = false,defaultValue = "") String q,
@RequestParam(name = "sortby", required = false, defaultValue = "companyId") String sortby,
@RequestParam(name = "order", required = false, defaultValue = "desc") String order,
@RequestHeader(value = "Accept-Language", defaultValue = "ar") String lang ) {

        
        if(sortby.equalsIgnoreCase("countryName")) {
            if(lang.equalsIgnoreCase("en")) {
                sortby="countryNameEn"; 
            }else
            if(lang.equalsIgnoreCase("ar")) {
                sortby="countryNameAr";
            }else
            if(lang.equalsIgnoreCase("fr")) {
                sortby="countryNameFr";
        }
于 2019-04-03T07:45:26.960 回答