View scoped managed bean with setPropertyActionListener - jsf-2

I cant seem to get the view scoped managed bean to work with setPropertyActionListener:
<h:commandButton value="Edit" action="edit-company.xhtml">
<f:setPropertyActionListener target="#{companyHolder.item}" value="#{company}"/>
</h:commandButton>
This works fine if companyHolder is session or request scoped but doesnt work if its view scoped. Is this normal?

A brand new view scoped bean is been created when a new view is created. The target view holds a different instance of the view scoped bean than where the property is been set by the action method on the initial view with the form.
This is at first sight indeed unintuitive, but that's how the view scope works. A view scoped bean lives as long as the view lives. It makes sense after all.
Your best bet is using <f:param> instead of <f:setPropertyActionListener> and let the target view set it by <f:viewParam>.
E.g.
<h:commandButton value="Edit" action="edit-company.xhtml">
<f:param name="companyId" value="#{company.id}"/>
</h:commandButton>
with
<f:metadata>
<f:viewParam name="companyId" value="#{bean.company}" required="true" />
</f:metadata>
and
#ManagedBean
#ViewScoped
public class Bean {
private Company company;
// ...
}
and
#FacesConverter(forClass=Company.class)
public class CompanyConverter implements Converter {
#Override
public void getAsObject(FacesContext context, UIComponent component, Object value) throws ConverterException {
try {
return companyService.find(Long.valueOf(value));
} catch (Exception e) {
throw new ConverterException(new FacesMessage(
String.format("Cannot convert %s to Company", value)), e);
}
}
// ...
}
As a completely different alternative, you can also just navigate back to the same view by returning void or null and render the include conditionally.
<ui:include src="#{bean.editmode ? 'edit' : 'view'}.xhtml" />
This however doesn't work if you require to support GET instead of POST (for which you would need to replace <h:commandButton> by <h:button> by the way).

Related

JSF 2.2 + CDI CRUD Functionality [duplicate]

I have started learning JSF, but sadly most tutorials out there present only a log in or a register section.
Can you point me to some more in depth examples? One thing I'm interested in is a page presenting a list of products. I'm on page home and I press on page products so that I can see the latest products added. And every time I visit the page, the product list will be created from the latest entries in the database. How can I handle this?
One way to solve this would be to create a session scoped managed bean in which I would place different entities updated through other managed beans. I found this kind of approach in some tutorials, but it seems quite difficult and clumsy.
Which would be the best approach to solve a thing like this? What is the correct usage of session scope in two-page master-detail user interface?
What is the correct usage of session scope
Use it for session scoped data only, nothing else. For example, the logged-in user, its settings, the chosen language, etcetera.
See also:
How to choose the right bean scope?
And every time I visit the page, the product list will be created from the latest entries in the database. How can I handle this?
Typically you use the request or view scope for it. Loading of the list should happen in a #PostConstruct method. If the page doesn't contain any <h:form>, then the request scope is fine. A view scoped bean would behave like a request scoped when there's no <h:form> anyway.
All "view product" and "edit product" links/buttons which just retrieve information (i.e. idempotent) whould be just plain GET <h:link> / <h:button> wherein you pass the entity identifier as a request parameter by <f:param>.
All "delete product" and "save product" links/buttons which will manipulate information (i.e. non-idempotent) should perform POST by <h:commandLink>/<h:commandButton> (you don't want them to be bookmarkable/searchbot-indexable!). This in turn requires a <h:form>. In order to preserve the data for validations and ajax requests (so that you don't need to reload/preinitialize the entity on every request), the bean should preferably be view scoped.
Note that you should basically have a separate bean for each view and also note that those beans doesn't necessarily need to reference each other.
So, given this "product" entity:
#Entity
public class Product {
#Id
private Long id;
private String name;
private String description;
// ...
}
And this "product service" EJB:
#Stateless
public class ProductService {
#PersistenceContext
private EntityManager em;
public Product find(Long id) {
return em.find(Product.class, id);
}
public List<Product> list() {
return em.createQuery("SELECT p FROM Product p", Product.class).getResultList();
}
public void create(Product product) {
em.persist(product);
}
public void update(Product product) {
em.merge(product);
}
public void delete(Product product) {
em.remove(em.contains(product) ? product : em.merge(product));
}
// ...
}
You can have this "view products" on /products.xhtml:
<h:dataTable value="#{viewProducts.products}" var="product">
<h:column>#{product.id}</h:column>
<h:column>#{product.name}</h:column>
<h:column>#{product.description}</h:column>
<h:column>
<h:link value="Edit" outcome="/products/edit">
<f:param name="id" value="#{product.id}" />
</h:link>
</h:column>
</h:dataTable>
#Named
#RequestScoped
public class ViewProducts {
private List<Product> products; // +getter
#EJB
private ProductService productService;
#PostConstruct
public void init() {
products = productService.list();
}
// ...
}
And you can have this "edit product" on /products/edit.xhtml:
<f:metadata>
<f:viewParam name="id" value="#{editProduct.product}"
converter="#{productConverter}" converterMessage="Unknown product, please use a link from within the system."
required="true" requiredMessage="Bad request, please use a link from within the system."
/>
</f:metadata>
<h:messages />
<h:form rendered="#{not empty editProduct.product}>
<h:inputText value="#{editProduct.product.name}" />
<h:inputTextarea value="#{editProduct.product.description}" />
...
<h:commandButton value="save" action="#{editProduct.save}" />
</h:form>
#Named
#ViewScoped
public class EditProduct {
private Product product; // +getter +setter
#EJB
private ProductService productService;
public String save() {
productService.update(product);
return "/products?faces-redirect=true";
}
// ...
}
And this converter for <f:viewParam> of "edit product":
#Named
#RequestScoped
public class ProductConverter implements Converter {
#EJB
private ProductService productService;
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if (value == null || value.isEmpty()) {
return null;
}
try {
Long id = Long.valueOf(value);
return productService.find(id);
} catch (NumberFormatException e) {
throw new ConverterException("The value is not a valid Product ID: " + value, e);
}
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (value == null) {
return "";
}
if (value instanceof Product) {
Long id = ((Product) value).getId();
return (id != null) ? String.valueOf(id) : null;
} else {
throw new ConverterException("The value is not a valid Product instance: " + value);
}
}
}
You can even use a generic converter, this is explained in Implement converters for entities with Java Generics.
See also:
How to navigate in JSF? How to make URL reflect current page (and not previous one)
JSF Controller, Service and DAO
JSF Service Layer
How to inject #EJB, #PersistenceContext, #Inject, #Autowired, etc in #FacesConverter?
Communication in JSF 2.0 - Contains several examples/hints
As a small improvement to what BalusC recommended, sometimes you can remove the required / requiredMessage part from the <f:viewParam> of your "details" screen and instead use the conditional rendering of the editing form (as BalusC did) with a reverse condition for recommending a specific link for the "list/master" screen or, even use a viewAction that would test the param and force a redirect to that list.

Dialog close instanciate Bean ViewScoped

I have a form where I have a button, when I click on that button, a Dialog opens to select a value and then my dialog close.
But, doing this my Bean (#ViewScoped) is called again (re-instantiated) and I lose my information that I previous entered on page.
I searched and I found a similar behaviour (http://forum.primefaces.org/viewtopic.php?f=3&t=38235) but no answer.
I initialize my bean with constructor but I don't know if this is the problem.
#ManagedBean(name="exameBean")
#ViewScoped
public class ExameBean implements Serializable {
public ExameBean(){
exame = new Exame();
exames = new ArrayList<Exame>();
}
public void selecionaPaciente() {
RequestContext.getCurrentInstance().openDialog("/pages/SelecionaPaciente");
}
public void retornaPaciente(Paciente paciente) {
RequestContext.getCurrentInstance().closeDialog(paciente);
}
public void pacienteSelecionado(SelectEvent event) {
exame.setPaciente((Paciente) event.getObject());
}
}
SelecionaPaciente.xhtml
<p:column headerText="Selecionar">
<p:commandButton icon="ui-icon-search" actionListener="#{exameBean.retornaPaciente(lista)}" />
</p:column>
May you need to use #SessionScoped, when you use #ViewScoped and show a dialog, you lose the actual instance of you MB. I had the same problem today and i solved using a init method annoted with #PostConstruct (To Load all my data ) and annotate with #SessionScoped to use and manage my data loaded from init().

JSF2.0 backing bean setter not invoked when using dataTable

I have a screen in which am using
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:body>
<h:form>
<f:event listener="#{pageload.getPageLoad}" type="preRenderView" />
<h:dataTable value="#{pageload.fieldConfig}" var="field"
columnClasses="lblFirstCol,lblSecondCol,lblThirdCol,lblFourthCol" id="table1" styleClass="tblSecond" >
<h:column >
<h:outputText value="#{field.label_name}" />
</h:column>
<h:column>
<h:inputText value="#{searchdevice.device.terminal_name}" />
</h:column>
</h:dataTable>
<h:commandButton value="Submit" action="#{searchdevice.searchButtonAction}"/>
</h:form>
</h:body>
And my backing bean
#ManagedBean(name="pageload")
#RequestScoped
public class PageLoadBean {
private List<FieldConfigVO> fieldconfig;
//getters and setters
// method to populate the ArrayList
public void getPageLoad(){
//getting populated from Database
fieldconfig = common.getFieldConfig("001");
}
}
The other input bean
#ManagedBean(name="searchdevice")
#RequestScoped
public class SearchDeviceBean {
private DeviceVO device;
public SearchDeviceBean() {
device = new DeviceVO();
}
public DeviceVO getDevice() {
return device;
}
public void setDevice(DeviceVO device) {
this.device = device;
}
public String searchButtonAction(){
System.out.println(device.getTerminal_name()+"****TERMINAL NAME******");
FacesContext context = FacesContext.getCurrentInstance();
if (context.getMessageList().size() > 0) {
return(null);
}else {
return("success");
}
}
}
My Device Object has the terminal_name property.I have a command button which invokes method in SearchDeviceBean and on submitting the form whatever value I enter doesn't get populated
Any help appreciated
You're performing data initialization logic in preRenderView event. This is the wrong place for code which needs to prepare the model for the postback. When JSF needs to update the model values during form submit, it is encountering a completely empty fieldConfig and therefore JSF can't set the submitted/converted/validated values in there. The fieldConfig is in your case only prepared during a later phase, the render response phase, which is thus too late.
You need to initialize it in #PostConstruct instead. It's invoked immediately after bean's construction and dependency in jection. Get rid of the whole <f:event> altogether and put a #PostConstruct annotation on the getPageLoad() method. I'd by the way also rename that method to init() or loadFieldConfig() as it isn't a getter method at all and therefore a very confusing name to other people reading/maintaining your code.
See also:
When to use f:viewAction / preRenderView versus PostConstruct?

<h:selectOneMenu> doesn't save on the bean the value selected

I have problems with SelectOneMenu. I write this:
<h:selectOneMenu id="listaEstados"
styleClass="comboboxStyle"
value="#{detalleSistemaBean.sistema.indEstado}"
immediate="true">
<f:selectItems value="#{detalleSistemaBean.indEstados}" />
</h:selectOneMenu>
<h:commandButton id ="SubmitModificar"
value="Modificar"
styleClass="botonPeque"
action="#{detalleSistemaBean.modificaSistema}">
</h:commandButton>
But when I choose one value from the list "indEstados" and I submit the form, the bean "sistema.indEstado" doesn't change. I have seen that the bean property changes just before the method modificaSistema, but inside this method (where I have a database connection and a sql sentence), "sistema.indEstado" returns to its original value. Why this happens? I have tried to save the value using valueChangeListener, and that works, but I guess that is not a neat solution.
That can happen when you're doing data loading inside the getter method instead of inside the (post)constructor of the bean class.
Fix your managed bean code to not do anything else inside getter methods than just returning the property.
I.e. do not do
public Sistema getSistema() {
return sistemaService.find(someSistemaId);
}
but rather do
private Sistema sistema;
#PostConstruct
public void init() {
sistema = sistemaService.find(someSistemaId);
}
public Sistema getSistema() {
return sistema;
}
Can you try without setting
immediate="true"
JSF commandButton with immediate="true"

Get access to session scoped CDI bean from request scoped CDI Bean

I have already one session scoped CDI bean, which keeps currently logged in user data.
Now, from another, request scoped I would like to access to this bean to get some data. I have some operation to do, which is dependent on user login. That's the only information I need.
How to access it?
AccountBean.java:
#Named("accountBean")
#SessionScoped
public class AccountBean implements Serializable {
private static final long serialVersionUID = 16472027766900196L;
#Inject
AccountService accountService;
private String login;
private String password;
// getters and setters ommited
}
Part of login.xhtml:
<h:form>
<h:panelGrid columns="2">
#{msgs.loginPrompt}
<h:inputText id="login" value="#{accountBean.login}" />
#{msgs.passwordPrompt}
<h:inputSecret id="password" value="#{accountBean.password}" />
<h:commandButton value="#{msgs.loginButtonText}"
action="#{accountBean.login}" />
</h:panelGrid>
</h:form>
SearchBean.java:
#Named("searchBean")
#RequestScoped
public class SearchBean {
#Inject AccountBean accountBean;
// some other stuff
}
Just #Inject it.
#Inject
private Bean bean;
Note that this isn't available in the constructor of the receiving bean (it's not possible to inject something in an unconstructed instance, you see). The earliest access point is a #PostConstruct method.
#PostConstruct
public void init() {
bean.doSomething();
}

Resources