简体   繁体   English

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

[英]Can we validate @RequestParam value with a pattern

i have a requirement, where in i need to validate my @RequestParam such that it is matched with my pattern 我有一个要求,我需要在哪里验证我的@RequestParam ,以便它与我的模式匹配

Example : 示例:

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

It should be very easy: 应该很容易:

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

use @DateTimeFormat 使用@DateTimeFormat

@RequestMapping(value = "/someTest")
public Object sendWishes(@RequestParam("birthDate") @DateTimeFormat(pattern="YYYYMMDD") LocalDate birthDate){ //Your code goes here }

InitBinder will serve purpose. InitBinder将用于服务目的。 You Should have following init binding code in your controller: 您应该在控制器中具有以下init绑定代码:

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

    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}

after that you can get birthDate in your specified YYYYMMDD as date object: 之后,您可以在指定的YYYYMMDD中将birthDate作为日期对象获取:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM