Tom*_*ker 44 java spring spring-mvc
对于表示字符串,数字和布尔值的请求参数,Spring MVC容器可以将它们绑定到开箱即用的类型属性.
你如何让Spring MVC容器绑定一个表示Date的请求参数?
说到这一点,Spring MVC如何确定给定请求参数的类型?
谢谢!
Art*_*ald 64
Spring MVC如何确定给定请求参数的类型?
Spring使用ServletRequestDataBinder绑定其值.该过程可以描述如下
/**
* Bundled Mock request
*/
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("name", "Tom");
request.addParameter("age", "25");
/**
* Spring create a new command object before processing the request
*
* By calling <COMMAND_CLASS>.class.newInstance();
*/
Person person = new Person();
Run Code Online (Sandbox Code Playgroud)
...
/**
* And Then with a ServletRequestDataBinder, it bind the submitted values
*
* It makes use of Java reflection To bind its values
*/
ServletRequestDataBinder binder = ServletRequestDataBinder(person);
binder.bind(request);
Run Code Online (Sandbox Code Playgroud)
在幕后,DataBinder实例在内部使用BeanWrapperImpl实例,该实例负责设置命令对象的值.使用getPropertyType方法,它将检索属性类型
如果您看到上面提交的请求(当然,通过使用模拟),Spring将调用
BeanWrapperImpl beanWrapper = new BeanWrapperImpl(person);
Clazz requiredType = beanWrapper.getPropertyType("name");
Run Code Online (Sandbox Code Playgroud)
然后
beanWrapper.convertIfNecessary("Tom", requiredType, methodParam)
Run Code Online (Sandbox Code Playgroud)
Spring MVC容器如何绑定表示Date的请求参数?
如果您有需要特殊的转换数据的人类友好的表示,你必须注册一个属性编辑器例如,java.util.Date不知道什么13/09/2010是,这样你就告诉Spring
Spring,使用以下PropertyEditor转换此人性化日期
binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
public void setAsText(String value) {
try {
setValue(new SimpleDateFormat("dd/MM/yyyy").parse(value));
} catch(ParseException e) {
setValue(null);
}
}
public String getAsText() {
return new SimpleDateFormat("dd/MM/yyyy").format((Date) getValue());
}
});
Run Code Online (Sandbox Code Playgroud)
当调用convertIfNecessary方法时,Spring会查找任何注册的PropertyEditor,它负责转换提交的值.要注册您的PropertyEditor,您可以
春天3.0
@InitBinder
public void binder(WebDataBinder binder) {
// as shown above
}
Run Code Online (Sandbox Code Playgroud)
旧式弹簧2.x.
@Override
public void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {
// as shown above
}
Run Code Online (Sandbox Code Playgroud)
Mir*_*ciu 31
作为Arthur非常完整的答案的补充:在简单的Date字段的情况下,您不必实现整个PropertyEditor.您只需使用CustomDateEditor,您只需传递要使用的日期格式:
//put this in your Controller
//(if you have a superclass for your controllers
//and want to use the same date format throughout the app, put it there)
@InitBinder
private void dateBinder(WebDataBinder binder) {
//The date format to parse or output your dates
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
//Create a new CustomDateEditor
CustomDateEditor editor = new CustomDateEditor(dateFormat, true);
//Register it as custom editor for the Date type
binder.registerCustomEditor(Date.class, editor);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
51482 次 |
最近记录: |