SpringMVC杂记(四) 数据绑定

本文详细介绍了SpringMVC中的数据绑定技术,包括使用PropertyEditor接口进行数据转换、通过Converter接口实现字符串到对象的转换、如何全局配置数据绑定以及异常处理等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SpringMVC杂记(四) 数据绑定

1) 使用java.beans.PropertyEditor接口
如一个表单类

public class UserInfoForm {

private String username;
private String password;

// getter and setter ...
}

在同一个包下新建一个类 UserInfoFormEditor,这个类名很重要
名字是XxxEditor, Xxx当然是指要编辑的类名字啦。

public class UserInfoFormEditor extends PropertyEditorSupport {

@Override
public String getAsText() {
UserInfoForm form = (UserInfoForm) super.getValue();
return form.getUsername() + "@@" + form.getPassword();
}

@Override
public void setAsText(String text) throws IllegalArgumentException {
UserInfoForm value = new UserInfoForm();
String[] infos = text.split("@@");
value.setUsername(infos[0]);
value.setPassword(infos[1]);
setValue(value);
}
}


2) 如果Editor类的名字不遵守上面的规范的话。 就只能可以在Controller中注册一下了。

@Controller
@RequestMapping("/test")
public class UserInfoController {

@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(UserInfoForm.class, new UserInfoFormEditor());
}
}


3) 如果想把Editor注册成全局性质的,而不仅仅对每一个固定的Controller起作用。
Controller类实现WebBindingInitializer接口即可。

@Controller
@RequestMapping("/test")
public class UserInfoController implements WebBindingInitializer {

@InitBinder
public void initBinder(WebDataBinder binder, WebRequest request) {
binder.registerCustomEditor(UserInfoForm.class, new UserInfoFormEditor());
}
}


4) org.springframework.core.convert.converter.Converter接口。
这个接口在Spring3.x时代才加入进来。 但是用法确实简单明了。

首先实现

public class String2UserInfoFormConverter implements Converter<String, UserInfoForm> {

public UserInfoForm convert(String source) {
UserInfoForm form = new UserInfoForm();
form.setUsername(source.split("@@")[0]);
form.setPassword(source.split("@@")[1]);
return form;
}
}


再在spring mvc的配置文件添加以下内容,就可完成全局配置。 特别推荐这种方式。

<mvc:annotation-driven conversion-service="conversion-service" />

<bean id="conversion-service"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="com.wicresoft.jpo.demo.converter.String2UserInfoFormConverter" />
</list>
</property>
</bean>


5) 数据绑定异常处理。如果某些错误需要特别处理而又不在全局exceptionResolver指定的话。
可以把Controller也实现为一个import org.springframework.web.servlet.HandlerExceptionResolver
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值