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