[英]How to provide expression for @RequestParam's defaultValue
I have a controller where a RequestParam is used. 我有一个控制器,使用RequestParam。 Like this
像这样
@RequestMapping("/hello")
public ModelAndView process(
@RequestParam(value = "startDate",
required = false,
defaultValue="yesterday()") startDate)
If the startDate
is not specified a defaultValue
is used. 如果未指定
startDate
则使用defaultValue
。 But in my case the value should be dynamic eg now()
or yesterday()
. 但在我的情况下,值应该是动态的,例如
now()
或yesterday()
。 Is there any way to specify an expression eg method of class to return the value? 有没有办法指定一个表达式,例如类的方法来返回值?
I am too lazy to use code like this everywhere 我懒得到处都用这样的代码
startDate=startDate!=null ? startDate : new Date()
UPDATE Ideally I would like to write custom expression to provide eg start of current week or end of current month if the date is not specified 更新理想情况下,如果未指定日期,我想编写自定义表达式以提供例如当前周的开始或当月的结束
As explain here https://stackoverflow.com/a/22523299/636472 : 在这里解释https://stackoverflow.com/a/22523299/636472 :
You can handle your case by create a behavior for a 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
The defaultValue has to be a final static
expression. defaultValue必须是
final static
表达式。 However there is a thing which you can do by using a custom annotation. 但是,您可以使用自定义注释来执行此操作。
eg 例如
create a custom annotation @customAnno
apply this annotation to which ever methods you want. 创建自定义注释
@customAnno
将此注释应用于您想要的方法。
using aspect @before("@customAnno")
catch this method and check whether it have the value you want or you change the value you want at runtime. 使用aspect
@before("@customAnno")
捕获此方法并检查它是否具有所需的值,或者在运行时更改所需的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.