如何在spring中给requestparam中的默认日期值

yaS*_*SIR 6 spring spring-mvc

@RequestMapping(value = "/getSettlements", method = RequestMethod.GET, headers = "Accept=application/json")
  public @ResponseBody
            Collection<Settlement> getSettlements
            (@RequestParam(value = "startDate") String startDate,
            @RequestParam(value = "endDate") String endDate,
            @RequestParam(value = "merchantIds", defaultValue = "null") String merchantIds)
Run Code Online (Sandbox Code Playgroud)

如何在defaultValue中提供今天的日期?它只需要不变.

小智 13

@InitBinder
public void initBinder(WebDataBinder binder) throws Exception {
    final DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    final CustomDateEditor dateEditor = new CustomDateEditor(df, true) {
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            if ("today".equals(text)) {
                setValue(new Date());
            } else {
                super.setAsText(text);
            }
        }
    };
    binder.registerCustomEditor(Date.class, dateEditor);
}
Run Code Online (Sandbox Code Playgroud)
@RequestParam(required = false, defaultValue = "today") Date startDate
Run Code Online (Sandbox Code Playgroud)


ygl*_*odt 5

如果您使用LocalDate,您可以创建一个默认值,如下所示:

@RequestParam(name = "d", defaultValue = "#{T(java.time.LocalDate).now()}", required = true) LocalDate d)
Run Code Online (Sandbox Code Playgroud)


alf*_*sin 0

由于您收到一个字符串,您可以使用任何您想要的日期格式,稍后使用格式来提取日期