我们可以用模式验证@RequestParam值吗

use*_*890 4 java spring spring-mvc

我有一个要求,在哪里我需要验证我的身份@RequestParam,使其与我的模式匹配

范例:

 @RequestMapping(value = "/someTest")
  public Object sendWishes(@RequestParam("birthDate") String birthDate)

    {
      // i need birthDate to be a valid date format in YYYYMMDD format
      // if its not valid it should not hit this method
    }
Run Code Online (Sandbox Code Playgroud)

Jai*_*o99 6

它应该很容易:

  @RequestMapping(value = "/someTest?birthDate={birthDate}")
  public Object sendWishes(@Valid @Pattern(regexp = "you-pattern-here") @RequestParam("birthDate") String birthDate)

  {
      // i need birthDate to be a valid date format in YYYYMMDD format
      // if its not valid it should not hit this method
  }
Run Code Online (Sandbox Code Playgroud)


Pra*_*kam 1

InitBinder 将达到目的。您的控制器中应该有以下初始化绑定代码:

@InitBinder
public void initBinder(WebDataBinder binder) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("YYYYMMDD");

    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
Run Code Online (Sandbox Code Playgroud)

之后,您可以在指定的 YYYYMMDD 中获取birthDate作为日期对象:

@RequestMapping(value = "/someTest")
public Object sendWishes(@RequestParam("birthDate") Date birthDate)
Run Code Online (Sandbox Code Playgroud)