我有一个要求,我需要验证我的@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
}
答案 0 :(得分: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
}
答案 1 :(得分:2)
使用@DateTimeFormat
@RequestMapping(value = "/someTest")
public Object sendWishes(@RequestParam("birthDate") @DateTimeFormat(pattern="YYYYMMDD") LocalDate birthDate){ //Your code goes here }
答案 2 :(得分:1)
InitBinder将用于服务目的。您应该在控制器中有以下init绑定代码:
@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("YYYYMMDD");
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
之后,您可以在指定的YYYYMMDD中将birthDate作为日期对象:
@RequestMapping(value = "/someTest")
public Object sendWishes(@RequestParam("birthDate") Date birthDate)