How to present a list of categories stored in database in JSF correctly

ぃ、小莉子 提交于 2019-12-13 08:36:59

问题


I am making an application where I am going to register questions. Each question has a relationship with one or more categories so I need a way in the register question form to select which categories it belongs to.

I am thinking of using one of the selectMany... components from JSF for the task. I could retrieve the list of all categories in the database (only 9) and then bind that list to a f:selectItems component. Then the itemValue of each selectItem must be the id of the category. I will also need a second list containing all the selected id's of the categories and at last do some sort of query against the database again with each id and add it to the list ....which again is set on the question.

I do not need a explanation on how to retrieve the list etc. but I could need some help if this approach is any good? Alternatives is well accepted:=)


回答1:


Make List<Category> a property of the Question entity.

@Entity
public class Question {

    @OneToMany
    private List<Category> categories;

    // ...
}

with

<h:selectManyMenu value="#{question.categories}" converter="#{categoryConverter}">
    <f:selectItems value="#{data.categories}" />
</h:selectManyMenu>

You only need to supply a converter for Category class.

@ManagedBean
@RequestScoped
public class CategoryConverter implements Converter {

    @EJB
    private CategoryService categoryService;

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if (!(value instanceof Category) || ((Category) value).getId() == null) {
            return null;
        }

        return String.valueOf(((Category) value).getId());
    }

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        if (value == null || !value.matches("\\d+")) {
            return null;
        }

        return categoryService.find(Long.valueOf(value));
    }

}

(note: it's until JSF 2.2 not possible to inject an @EJB in a @FacesConverter, that's why it's a @ManagedBean instead, see also Communication in JSF 2.0 - Converting and validating GET request parameters)

You don't need to duplicate the selected items in the managed bean or something else.



来源:https://stackoverflow.com/questions/8202569/how-to-present-a-list-of-categories-stored-in-database-in-jsf-correctly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!