问题
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