1

我将 rich:pickList 替换为 selectManyListbox 进行测试,将值提交到服务器时仍然显示错误:“验证错误:值无效”。我还设置了断点来调试 StaffConverter (getAsobject),但系统从不调用它。请让我知道为什么我的转换器从未调用过的一些原因,并建议我如何解决这个问题。谢谢

xhtml 文件:

<h:selectManyListbox value="#{reportController.selectedStaffList}" converter="staffConverter">
   <f:selectItems value="#{reportController.staffList}" 
                  var="item" itemValue="#{item}" itemLabel="#{item.name}" />
</h:selectManyListbox>

<rich:pickList value="#{reportController.selectedStaffList}" converter="staffConverter" sourceCaption="Available flight" targetCaption="Selected flight" listWidth="195px" listHeight="100px" orderable="true">
   <f:selectItems value="#{reportController.staffList}" var="item" itemValue="#{item}" itemLabel="#{item.name}" />
</rich:pickList>

我的转换器:

@FacesConverter(forClass = Staff.class)
public static class StaffConverter implements Converter {

    public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
        if (value == null || value.length() == 0) {
            return null;
        }
        StaffController controller = StaffController.getInstance();
        return controller.facade.find(Staff.class, getKey(value));
    }

    java.lang.Integer getKey(String value) {
        java.lang.Integer key;
        key = Integer.valueOf(value);
        return key;
    }

    String getStringKey(java.lang.Integer value) {
        StringBuffer sb = new StringBuffer();
        sb.append(value);
        return sb.toString();
    }

    public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
        if (object == null) {
            return null;
        }
        if (object instanceof Staff) {
            Staff o = (Staff) object;
            return getStringKey(o.getStaffCode());
        } else {
            throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName()
                    + "; expected type: " + StaffController.class.getName());
        }
    }
}

我在 Staff 中实现了 equals 方法:

@Override
public boolean equals(Object object) {
    if (!(object instanceof Staff)) {
        return false;
    }
    Staff other = (Staff) object;
    return (this.staffCode == other.staffCode);
}
4

2 回答 2

2

只是为了将它发布给像我这样喜欢在 google 或 stackoverflow 上搜索开发问题解决方案的人...

我多次遇到这个问题,具体取决于我在转换器中使用的 pojos 类型......最后我想我找到了一个优雅的解决方案。在我的例子中,我直接使用 JPA 实体类,因为我想保存 DTO 层。好吧,对于一些实体,rich:pickList 可以工作,而其他实体则不能......我也将其追踪到 equals 方法。例如,在下面的示例中,它不适用于 userGroupConverter bean。

我的解决方案是简单地内联覆盖equals方法,因此来自实体(我经常使用lombok)的那个是不变的,根本不需要更改!所以在我下面的转换器中,我只比较等号中的名称字段:

xhtml:

    <rich:pickList id="pickListUserGroupSelection"
        value="#{usersBean.selectedUserGroups}" switchByDblClick="true"
        sourceCaption="Available user groups" targetCaption="Groups assigned to user"
        listWidth="365px" listHeight="100px" orderable="false"
        converter="#{userGroupConverter}"
        disabled="#{!rich:isUserInRole('USERS_MAINTAIN')}">

        <f:validateRequired disabled="true" />
        <rich:validator disabled="true" />

        <f:selectItems value="#{usersBean.userGroups}" var="userGroup"
            itemValue="#{userGroup}"
            itemLabel="#{userGroup.name}" />

        <f:selectItems value="#{usersBean.selectedUserGroups}" var="userGroup"
            itemValue="#{userGroup}"
            itemLabel="#{userGroup.name}" />

    </rich:pickList>
    <rich:message for="pickListUserGroupSelection" />

转换器:

package ...;

import ...

/**
 * JSF UserGroup converter.<br>
 * Description:<br>
 * JSF UserGroup converter for rich:pickList elements.<br>
 * <br>
 * Copyright: Copyright (c) 2014<br>
 */
@Named
@Slf4j
@RequestScoped // must be request scoped, as it can change every time!
public class UserGroupConverter implements Converter, Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 9057357226886146751L;

    @Getter
    Map<String, UserGroup> groupMap;

    @Inject
    MessageUtil messageUtil;

    @Inject
    UserGroupDao userGroupDao;

    @PostConstruct
    public void postConstruct() {

        groupMap = new HashMap<>();

        List<UserGroup> userGroups;
        try {
            userGroups = userGroupDao.findAll(new String[] {UserGroup.FIELD_USER_ROLE_NAMES});

            if(userGroups != null) {

                for (UserGroup userGroup : userGroups) {

                    // 20150713: for some reason the UserGroup entity's equals method is not sufficient here and causes a JSF validation error
                    // "Validation Error: Value is not valid". I tried this overridden equals method and now it works fine :-)
                    @SuppressWarnings("serial")
                    UserGroup newGroup = new UserGroup() {

                        @Override
                        public boolean equals(Object obj){
                            if (!(obj instanceof UserGroup)){
                                return false;
                            }

                            return (getName() != null)
                                 ? getName().equals(((UserGroup) obj).getName())
                                 : (obj == this);
                        }
                    };
                    newGroup.setName(userGroup.getName());

                    groupMap.put(newGroup.getName(), newGroup);
                }
            }

        } catch (DaoException e) {

            log.error(e.getMessage(), e);

            FacesContext fc = FacesContext.getCurrentInstance();
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error initializing user group converter!", null);
            fc.addMessage(null, message);
        }
    }

    /*
     * (non-Javadoc)
     * @see javax.faces.convert.Converter#getAsObject(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.String)
     */
    @Override
    public UserGroup getAsObject(FacesContext context, UIComponent component,
            String value) {

        UserGroup ug = null;

        try {

            ug = getGroupMap().get(value);
        } catch (Exception e) {

            log.error(e.getMessage(), e);

            FacesContext fc = FacesContext.getCurrentInstance();
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Error converting user group!", null);
            fc.addMessage(null, message);
        }

        return ug;
    }

    /*
     * (non-Javadoc)
     * @see javax.faces.convert.Converter#getAsString(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.Object)
     */
    @Override
    public String getAsString(FacesContext context, UIComponent component,
            Object value) {

        String name = ((UserGroup) value).getName();

        return name;
    }

}

Brgds,玩得开心!

于 2015-07-13T11:03:27.700 回答
0

感谢 Brian 和 BalusC 的帮助。我通过在 selectManyListbox & rich:picklist 中添加命名转换器来解决我的问题,以便它们运行良好。但通常,我只使用@FacesConverter(forClass = Staff.class),并且不需要在 jsf 中添加命名转换器,因此它们仍然运行良好,除了 selectManyListbox & rich:picklist

于 2012-10-17T02:53:58.173 回答