<select name="occupation">
<option name="0">A occupaation</option>
<option name="1">Other occupaation</option>
<option name="2">Another occupaation</option>
</select>
Spring 使用 data-dinding 将您选择的 HTML 元素绑定到您的属性。使用的方法称为initBind
public class UserController extends BaseCommandController {
private OccupationRepository occupationRepository;
private CountryRepository countryRepository;
// getter's and setter's (retrieved by Dependency Injection supported by Spring)
public UserController() {
setCommandClass(User.class);
setValidator(new UserValidator());
}
public void initBind(HttpServletRequest request, ServletRequestDataBinder binder) {
binder.registerCustomPropertyEditor(Occupation.class, new PropertyEditorSupport() {
public void setAsText(String occupationId) {
// StringUtils belongs to jakarta-commons lang
if(StringUtils.isBlank(occupationId)) {
setValue(null);
return;
}
setValue(occupationRepository.getById(Integer.valueOf(occupationId)));
}
public String getAsText() {
if(getValue() == null)
return;
return String.valueOf(((Occupation) getValue()).getId());
}
});
// Same approach when binding Country
}
}
注意您可以通过分配 WebBindingInitializer 对象来替换 initBind 方法
public class UserBindingInitializer implements WebBindingInitializer {
private OccupationRepository occupationRepository;
private CountryRepository countryRepository;
// getter's and setter's (retrieved by Dependency Injection supported by Spring)
public void initBinder(WebDataBinder binder, WebRequest request) {
binder.registerCustomPropertyEditor(Occupation.class, new PropertyEditorSupport() {
public void setAsText(String occupationId) {
// StringUtils belongs to jakarta-commons lang
if(StringUtils.isBlank(occupationId)) {
setValue(null);
return;
}
setValue(occupationRepository.getById(Integer.valueOf(occupationId)));
}
public String getAsText() {
if(getValue() == null)
return;
return String.valueOf(((Occupation) getValue()).getId());
}
});
}
}
...
public class UserController extends BaseCommandController {
private OccupationRepository occupationRepository;
private CountryRepository countryRepository;
// getter's and setter's (retrieved by Dependency Injection supported by Spring)
public void setUserBindingInitializer(UserBindingInitializer bindingInitializer) {
setWebBindingInitializer(bindingInitializer);
}
还有您的 UserValidator(请注意,您的 Validator 对任何存储库一无所知)
public class UserValidator implements Validator {
public boolean supports(Class clazz) {
return clazz.isAssignableFrom(User.class);
}
public void validate(Object command, Errors errors) {
User user = (User) command;
if(user.getOccupation() == null)
errors.rejectValue("occupation", "errors.required", null);
if(user.getCountry() == null)
errors.rejectValue("country", "errors.required", null);
}
}