tags:

views:

167

answers:

1

Let's say that you have the following Facelet ( Using Facelets 1.1.12 ):

edit_item.xhtml which i access with edit_item.jsf

Now i have another page sending me to edit_item.jsf with the GET-paremeter ID the uri looks like this: http://mysite.com/edit_item.jsf?ID=200

How do you access a Bean and fetch the Information, and display this on the requesting page with JSF and Facelets? Is there a way to run a bean when a page loads?

+4  A: 

You can use the faces-config.xml configuration to inject the ID from the param map.

For this simple bean:

public class BeanWithId implements Serializable {
  private String id;
  private String info;

  private void populateInfo() {
    info = "Some info from data source for id=" + id;
  }

  public String getId() { return id; }

  public void setId(String id) {
    this.id = id;
    populateInfo();
  }

  public String getInfo() { return info; }
  public void setInfo(String info) { this.info = info; }

  public String save() {
    System.out.println("Saving changes to persistence store");
    return null; // no navigation
  }
}

You could inject the ID using this definition:

  <managed-bean>
    <managed-bean-name>beanWithId</managed-bean-name>
    <managed-bean-class>datasource.BeanWithId</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
    <managed-property>
      <property-name>id</property-name>
      <property-class>java.lang.String</property-class>
      <value>#{param.ID}</value>
    </managed-property>
  </managed-bean>

Facelets form:

<h:form>
  <p>ID: <h:outputText value="#{beanWithId.id}" /></p>
  <p>Info: <h:inputText value="#{beanWithId.info}" /></p>
  <p><h:commandLink action="#{beanWithId.save}" value="Save">
    <f:param name="ID" value="#{param.ID}" />
  </h:commandLink></p>
</h:form>

This isn't the only way to do it (you could look the ID up directly using the FacesContext for example).

McDowell
This is Exactly what I am looking for, thank you Very much. Im gonna report back once I've tested this!
Filip Ekberg
very cool answer. Thanks McDowell.
digitaljoel
Works kind of well, but once you press "Save" the param.ID is gone and you get an Internal Server Error saying there's no property "ID". How would you solve that? Seems like it doesn't matter if i add a navigation to return from Save, get that anyways. Suggestions?
Filip Ekberg
Should have tested the code! I switched the `commandButton` for a `commandLink` and added the `param` to that. I see you have another question on this - there are a few options here, so I'll post an answer there.
McDowell