在“创建新用户”的JSF页面中,我有一个SelectOneMenu,其中包含一个自定义转换器和一个noSelectionOption selectItem,如下所示:(省略了无关代码)
新用户.xhtml
新用户.xhtml
<h:form>
<h:selectOneMenu value="#{newUserController.user.department}"
required="true" converter="departmentConverter">
<f:selectItem itemLabel="Select a department" noSelectionOption="true"/>
<f:selectItems value="#{newUserController.departments}"
var="dep" itemLabel="#{dep.name}" itemValue="#{dep}"/>
</h:selectOneMenu>
<p:commandButton action="#{newUserController.saveUser}"
value="#{bundle.Save}"
ajax="false"/>
</h:form>
NewUserController.java
@ManagedBean
@ViewScoped
public class NewUserController implements Serializable {
private static final long serialVersionUID = 10L;
@EJB private UserBean userBean;
private List<Department> departments;
private User user;
public NewUserController () {
}
@PostConstruct
public void init(){
user = new User();
departments = userBean.findAllDepartments();
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public List<Department> getDepartments(){
return departments;
}
public String saveUser() {
// Business logic
}
}
DepartmentConverter.java
@FacesConverter(value="departmentConverter")
public class DepartmentConverter extends EntityConverter {
public DepartmentConverter(){
super(Department.class);
}
}
全能实体转换器
public class EntityConverter<E> implements Converter{
protected Class<E> entityClass;
public EntityConverter(Class<E> type) {
entityClass = type;
}
@Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
try {
InitialContext ic = new InitialContext();
UserBean ub = (UserBean)ic.lookup("java:global/CompetenceRegister/UserBean");
return ub.find(entityClass, getKey(value));
} catch (NamingException e) {
return null;
}
}
Long getKey(String value) {
Long key;
key = Long.valueOf(value);
return key;
}
String getStringKey(Long value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}
@Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof AbstractEntity) {
AbstractEntity e = (AbstractEntity) object;
return getStringKey(e.getId());
}
else
throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + entityClass.getName());
}
然而,当我提交表单并选择“选择一个部门”选项时,它会将标签发送到转换器的getAsObject方法中,而不是null,因此导致转换器在getKey中抛出异常(尝试将包含id的字符串转换为Long)。将selectItem的itemValue属性设置为null没有效果。除了转换器之外,集合中的项目完美运行。有人知道是什么原因造成了这种情况吗?
更新 我忘记提到的一个有趣的事情; 如果我从SelectOneMenu中删除转换器属性,则noSelectionAttribute将按照预期工作,但由于默认转换器不知道如何转换我的对象,因此在选择真正的部门时,提交将失败。这是否意味着noSelectionOption=true 应该发送其标签,并且某种程度上期望转换器处理它?
f:selectItem noSelectionOption
和f:selectItems var
是JSF2的标志。 - BalusC