13
@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.

0

4 Answers 4

21
@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
5

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)
2
  • I like the solution with the SpEL. Can you say what the T is doing here? Some kind of casting?
    – timguy
    Nov 29, 2022 at 11:23
  • 1
    T( type ) creates an instance of the given type.
    – yglodt
    Nov 29, 2022 at 15:08
2

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()}"

0

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

8
  • I want something like this @RequestParam(value = "merchantIds", defaultValue = date where date has been set up above as String date = new Date().toString(); but its giving error "attribute value can only be constant"
    – yaSIR
    Jul 17, 2013 at 7:21
  • You can add a private static String to the class and initialize it when the class loads and use it here.
    – Nir Alfasi
    Jul 17, 2013 at 7:27
  • thx for info.. I am doing the same .... priavte static String date = new Date().toString(); .... and using this date in my defaultValue but still its saying "attribute value can only be constant"
    – yaSIR
    Jul 17, 2013 at 7:30
  • Try adding final in the parameter declaration
    – Nir Alfasi
    Jul 17, 2013 at 7:36
  • same error ..even after doing private static final String date = new Date().toString();
    – yaSIR
    Jul 17, 2013 at 7:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.