我写了以下代码:
@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,但有一个例外:page.html应该提供与page1.html相同的结果。我正在寻找能使{number}成为可选项的东西,现在它是必需的。
我说有没有办法做到这一点?
/
答案 0 :(得分:15)
您可以使用以下内容:
@RequestParam(value = "name", defaultValue = "") Long name
请注意,您必须使用包装(如Long),而不是原语(如长)。
我希望这会有用。
答案 1 :(得分: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);
}
}
答案 2 :(得分:1)
您可能希望实现自定义WebArgumentResolver和注释@OptionalPathVariable并自行处理
答案 3 :(得分:0)
@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";
}