yaSIR
yaSIR

Reputation: 131

How to give default date values in requestparam in spring

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

How to give today's date in defaultValue ? It only takes constant.

Upvotes: 13

Views: 17481

Answers (4)

yglodt
yglodt

Reputation: 14551

If you are using LocalDate, you can create a default value like this:

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

Upvotes: 6

jfzr
jfzr

Reputation: 395

I tried pretty much every option, even using interceptors. But from far the easiest solution was to use SpEL. For Example: defaultValue = "#{new java.util.Date()}"

Upvotes: 2

jaiiye
jaiiye

Reputation: 211

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

@RequestParam(required = false, defaultValue = "today") Date startDate

Upvotes: 21

Nir Alfasi
Nir Alfasi

Reputation: 53565

Since you receive a string you can any date format you want and later on use formatting to extract the date

Upvotes: 0

Related Questions