JSF LInk to View Page
-
28-10-2019 - |
Question
I have a page with a data table. I want some of the items in the tables to be linked to a corresponding view page.
For example, right now I have a table with no links:
<h:dataTable var="bean" value="#{beanServiceImpl.beans}" border="1">
<h:column>#{bean.id}</h:column>
</h:dataTable>
I want to add hyperlinks to some entries and have them go to a view page showing them more info based on their id:
<h:dataTable var="bean" value="#{beanServiceImpl.beans}" border="1">
<h:column>
<a href="viewBean.xhtml?id=#{bean.id}">#{bean.id}</a>
</h:column>
</h:dataTable>
ViewBean.xhtml will contain something like this:
ViewBean.xhtml
<ul>
<li>ID: #{bean.id}</li>
<li>Field 1: #{bean.field1}</li>
<li>Field 2: #{bean.field2}</li>
</ul>
How do I accomplish something like this in JSF? I know that I'll have to write a controller to query the id for the other fields. But how do I make viewBean.xhtml run the business logic to get the other fields and render it?
Solution
The BalusC's answer is almost good, but will not work (edit: it works now).
You already know, how to add the value to the params. BTW, if I were you, I would not use <a href>
, but instead:
<h:link outcome='viewBean'>
<f:param name='id' value='#{bean.id}' />
</h:link>
Now you have to choices when it comes to catching the value. The simplest would be to add annotation above your id property:
@ManagedProperty("#{param.id}") // this will inject id from param into id
private Long id;
// (getters and setters are obligatory)
@PostConstruct // this will execute init() after id is injected
public void init() {
}
And the last thing: having a variable named "bean" has no more sense than calling it "variable" (or having a dog named Dog and cat named Cat). It carries no information and worse, it makes all the beans in your application indistinguishable (unless you build a legumes manager).
OTHER TIPS
I'll assume JSF 2.x. Add this to your Bean
@ManagedProperty(value="#{param.id}")
private Long id;
(this does basically a bean.setId(request.getParameter("id"))
whenever the view loads)
It'll be available in @PostConstruct
method of Bean
.
@PostConstruct
public void init() {
// Fill model based on id.
}
This is what I did.
<h:form>
<h:commandLink action="#{bean.populateBean}" value="#{bean.id}">
<f:setPropertyActionListener target="#{bean.id}" value="#{bean.id}" />
</h:commandLink>
</h:form>
In my Bean.java class, I added the action controller:
public String populateBean(){
Bean bean = BeanServiceImpl.getBean(id); //id was injected by the commandLink
this.field1 = tenure.getField1();
this.field2 = tenure.getField2();
return("viewBean");
}
My ViewBean.xhtml is the same:
<ul>
<li>ID: #{bean.id}</li>
<li>Field 1: #{bean.field1}</li>
<li>Field 2: #{bean.field2}</li>
</ul>