gpt4 book ai didi

binding - Spring MVC 绑定(bind)

转载 作者:行者123 更新时间:2023-12-04 19:20:08 27 4
gpt4 key购买 nike

我有以下命令对象:

public class User {
private Department department;
private String firstName;
private String lastName;
private String login;
private String password;
...
}

应该在jsp页面呈现:
<form:input path="lastName" />
<form:input path="department.name"/>
<form:input path="department.description"/>

因此,当我使用空的部门名称和部门描述提交时,Spring 会自动实例化具有空属性的对象部门。 (参见 https://jira.springframework.org/browse/SPR-6032 我会保留 autoGrowNestedPaths=true)

取回 Department object=null 的 User 对象需要做什么?

最佳答案

What is need to do for getting back User object where Department object=null?



如果您正在寻找特定于 Controller 的解决方案,请找到所有空的嵌套参数并将这些参数设置为不允许的字段。
@InitBinder(value="user")
public void bind(WebDataBinder dataBinder, WebRequest webRequest) {
List<String> emptyParams = new ArrayList<String>();
Iterator<String> itr = webRequest.getParameterNames();
while(itr.hasNext()) {
String name = itr.next();
if(name.startsWith("department.")) {
Object value = webRequest.getParameter(name);
if("".equals(value)) {
emptyParams.add(name);
}
}
}
if(!emptyParams.isEmpty()) {
dataBinder.setDisallowedFields(emptyParams.toArray(new String[emptyParams.size()]));
}
}

如果您正在寻找通用解决方案,请创建自定义数据绑定(bind)器并删除所有空的嵌套参数。
public class CustomDataBinder extends ServletRequestDataBinder {

@Override
protected void doBind(MutablePropertyValues mpvs) {
PropertyValue[] pvArray = mpvs.getPropertyValues();
for (PropertyValue pv : pvArray) {
boolean nestedProperty = PropertyAccessorUtils.isNestedOrIndexedProperty(pv.getName());
if(nestedProperty && "".equals(pv.getValue())) {
mpvs.removePropertyValue(pv);
}
}
super.doBind(mpvs);
}

}

要使用 CustomDataBinder,您必须拥有自定义 HandlerAdapter。
public class StandardAnnotationMethodHandlerAdapter extends AnnotationMethodHandlerAdapter    {
@Override
protected ServletRequestDataBinder createBinder(HttpServletRequest request, Object target, String objectName) throws Exception {
CustomDataBinder dataBinder = new CustomDataBinder (target, objectName);
return dataBinder;
}
}

关于binding - Spring MVC 绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4460874/

27 4 0
文章推荐: flash - 标签中的 classid 有什么作用?