Yavin
Yavin

Reputation: 455

Convert query string parameter to entity

I'm trying to do some of the most basic scenario i think.

On starting page there is a list of categories from database and after i click on category there should be a page with some details about that category (maybe print it name and some product etc.)

I was trying to do what BalusC did on ther blog post

I'm using java-ee-7, glasfish 4.1, hibernate 4.3.5

in index.xhtml i make link to category with parameter:

<h:link outcome="category.xhtml" value="#{category.name}">
    <f:param name="categoryId" value="#{category.id}"/>
</h:link>

Categories are printed just fine with query string categoryId parameter.

Then on category.xhtml i have:

<f:metadata>
    <f:viewParam name="categoryId" 
        value="#{categoryController.category}"
        converter="#{categoryConverter}" />
</f:metadata>

<h:body>
    Category name:

    <h:outputText value="#{categoryController.category.name}" />
    <!-- this one prints nothing -->

</h:body>

CategoryController code looks like this:

@Named
@RequestScoped
public class CategoryController {

    private Category category;

    public void setCategory(Category category) {
        this.category = category;
    }
    public Category getCategory() {
        return category;
    }
}

and the converter looks like this:

@Named
@RequestScoped
public class CategoryConverter implements Converter {

    @Inject
    private CategoryRepository categoryRepository;

    @Override
    public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String s) {
        return categoryRepository.find(Integer.parseInt(s));
    }

    @Override
    public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object o) {
        if (o == null || !(o instanceof Category)) {
            return null;
        }
        return ((Category) o).getId().toString();
    }
}

Making some test only getAsString method is invoked, but i think there should be getAsObject instead.

Statement <h:outputText value="#{categoryController.category.name}" /> prints nothing (it is probably null). How can i have Category entity in category.xhtml page?

--

To make it clear, i make it work with somethink like

<h:commandButton action="#{categoryController.showCategory(category)}" />

but this generate http post and i want to have simple get request. For me it would be just ridiculous that it would be only accessible through post.

In case something is missing, i make it accessible through github with stripped unnecessary code here: https://github.com/Yavin/jsf-entity-convert

Upvotes: 0

Views: 414

Answers (0)

Related Questions