How to provide expression for @RequestParam defaultValue

I have a controller that uses RequestParam. Like this

@RequestMapping("/hello")
public ModelAndView process(
        @RequestParam(value = "startDate", 
                      required = false, 
                      defaultValue="yesterday()") startDate)

      

If the parameter is startDate

not specified, it is used defaultValue

. But in my case the value should be dynamic, for example. now()

or yesterday()

. Is there a way to specify an expression eg. a class method to return a value?

I'm too lazy to use code like this everywhere

startDate=startDate!=null ? startDate : new Date()

      

UPDATE Ideally I would like to write my own expression to provide eg. the beginning of the current week or the end of the current month if no date is specified.

+4


source to share


2 answers


As explain here fooobar.com/questions/2047309 / ... :

You can handle your case by creating a behavior for the special word:

@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

      

+3


source


defaultValue must be an expression final static

. However, there is something you can do using custom annotation.

eg.



create custom annotation to @customAnno

apply that annotation you ever want.

using aspect @before("@customAnno")

, catch this method and check if it has the value you want or you change the value you want at runtime.

0


source







All Articles