This question already has answers here:
Creating master-detail pages for entities, how to link them and which bean scope to choose
(2 answers)
Closed 3 years ago.
I can't pass values between two managed beans of different pages.
I am implementing a search box JSF component in a Home page. I request some values and when the user hits search it goes to the search result page.
The search result page has a JSF component SEARCH RESUKTS which needs to access the selection in the managed bean which correspond to the search box from the home page.
I have tried using injection but it seams that the Managed BEan box is reintialized, showing the default value. I pick an interest from the search box, i.e. Cinema, then I click search which takes me to search result, I hope to see cinema but I see Sport the defualt value.
Please find the code below.
SEARCH RESULT MANAGED BEAN
import javax.el.ELContext;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
#ManagedBean
#ApplicationScoped
public class ExpSearchResultsMB {
/** Creates a new instance of ExpSearchResultsMB */
public ExpSearchResultsMB() {
}
#ManagedProperty(value="#{expSearchBoxMB.selectedValue}")
private String selectedValue; // +setter
#ManagedProperty(value="#{expSearchBoxMB.text}")
private String prova;
public String getProva() {
return prova;
}
public void setProva(String prova) {
this.prova = prova;
}
public String getSelectedValue() {
return selectedValue;
}
public void setSelectedValue(String selectedValue) {
this.selectedValue = selectedValue;
}
}
SEARCH BOX MANAGED BEAN
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedProperty;
#ManagedBean
#ApplicationScoped
public class ExpSearchBoxMB {
public Date date;
public List<String> interests=new ArrayList<String>();
public String selectedValue="Sport";
public String getSelectedValue() {
return selectedValue;
}
public void setSelectedValue(String selectedValue) {
this.selectedValue = selectedValue;
}
public List<String> getInterests() {
interests.add("Sport");
interests.add("Musin");
interests.add("Art");
interests.add("Thatre");
interests.add("Cinema");
return interests;
}
public void setInterests(List<String> interests) {
this.interests = interests;
}
I would appreciate any help.
Cheers
I would say debug and check if the correct value is set on selection change of interests.
If everythig is correct but still you see the incorrect results then try using the following code in ExpSearchResultsMB
FacesContext context = FacesContext.getCurrentInstance();
ExpSearchBoxMB expSearchBoxMBBean = (ExpSearchBoxMB) context.getApplication().evaluateExpressionGet(context, "#{expSearchBoxMB}", ExpSearchBoxMB.class);
expSearchBoxMBBean.getSelectedValue()
You can try this:
<h:panelGrid columns="2" >
<h:form>
<h:outputLabel for="prova" value="Prova: " />
<h:inputText binding="#{prova}" id="prova" />
<h:outputLabel for="interest" value="Interest: " />
<h:selectOneMenu binding="#{interest}" id="interest" >
<f:selectItems value="#{expSearchBoxMB.interests}" var="i"
itemLabel="#{i}" itemValue="#{i}" />
</h:selectOneMenu>
<h:button value="Search" outcome="Result">
<f:param name="prova" value="#{prova.value}" />
<f:param name="interest" value="#{interest.value}" />
</h:button>
</h:form>
</h:panelGrid>
Then in your ExpSearchResultsMB, you can get the value like this:
#ManagedBean
#ViewScoped
public class ExpSearchResultsMB {
private String interest;
private String prova;
private String statusMsg;
#PostConstruct
public void prepareResult() {
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
this.interest = request.getParameter("interest");
this.prova = request.getParameter("prova");
if (interest == null || prova == null) statusMsg = "Please provide all information";
else {
// Prepare result to show to the user
}
}
// Getters and Setters
}
If you use #RequestScoped for your ExpSearchResultsMB instead of #ViewScoped, you can use #ManagedProperty to get the submitted value as following:
#ManagedProperty(value="#{param.prova}"})
private String prova;
#ManagedProperty(value="#{param.interest}"})
private String interest;
Related
This question already has answers here:
Conversion Error setting value for 'null Converter' - Why do I need a Converter in JSF?
(2 answers)
Closed 7 years ago.
Inside my controller StudentController I have a variable Course course and I want to set this variable with the value, selected in a selectOneMenu, inside my JSF-page. Clicking the save-button would temporarily just call the JSF-page index (I will fill that part with my own code that will persist the student course, which will not be a problem).
The corresponding part in my JSF-page:
<h:form>
<h:panelGrid columns="2" style="margin-bottom:10px" cellpadding="5">
<p:outputLabel for="course" value="Select Course:" />
<p:selectOneMenu id="course" value="#{studentController.course}">
<f:selectItem itemLabel="--- Please Select ---" itemValue="" />
<f:selectItems value="#{studentController.courses}" var="course"
itemLabel="#{course.name}" itemValue="#{course}" />
</p:selectOneMenu>
</h:panelGrid>
<p:commandButton action="index?faces-redirect=true"
value="Save" icon="ui-icon-circle-check" />
</h:form>
The corresponding part in the controller:
#ManagedBean
#SessionScoped
public class StudentController {
// list contains available courses, is not empty
private List<Course> courses;
private Course course = new Course();
// getter, setter and other functionality
}
When I click the save-button, nothing happens. No error messages in my console, no redirecting.
How can I store the value, selected on the selectOneMenu inside my course variable?
In order to map value from <p:selectOneMenu to your java object you'll need to use jsf converter.
You can use generic converter without adding any dependencies
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import java.util.WeakHashMap;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
#FacesConverter(value = "entityConverter")
public class EntityConverter implements Converter {
private static Map<Object, String> entities = new WeakHashMap<Object, String>();
#Override
public String getAsString(FacesContext context, UIComponent component, Object entity) {
synchronized (entities) {
if (!entities.containsKey(entity)) {
String uuid = UUID.randomUUID().toString();
entities.put(entity, uuid);
return uuid;
} else {
return entities.get(entity);
}
}
}
#Override
public Object getAsObject(FacesContext context, UIComponent component, String uuid) {
for (Entry<Object, String> entry : entities.entrySet()) {
if (entry.getValue().equals(uuid)) {
return entry.getKey();
}
}
return null;
}
}
Then change your xhtml as
<p:selectOneMenu converter="entityConverter">
Now you'll have selected value in the managed bean.
I have two managedbean class(UserBean.java & HelloBean.java) and one index.xhthl class. In HelloBean.java class, I have used #ManagedProperty anotation for accessing the property of UserBean.java and I have a method within HelloBean.java class.
here, my classes:
UserBean.java
package com.bean;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
#ManagedBean(name="ubean", eager=true)
#SessionScoped
public class UserBean {
private String username;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
HelloBean.java
package com.bean;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
#ManagedBean(name="hellobean", eager=true)
#RequestScoped
public class HelloBean {
#ManagedProperty(value="#{ubean}")
private UserBean mbean;
private String username;
public String getUsername() {
if(mbean!=null){
username=mbean.getUsername();
}
return username;
}
public void setMbean(UserBean mbean) {
this.mbean = mbean;
}
public UserBean getMbean() {
return mbean;
}
public void showMsg(){
System.out.println("UserName :"+username);
}
}
And, index.xhtml
<body>
<h:form>
<h:inputText id="username" value="#{ubean.username}"></h:inputText>
<h:commandButton value="submit" action="#{hellobean.showMsg}"></h:commandButton>
</h:form>
</body>
I want to invoke the showMsg() method from index.xhtml class. The method is fired by clicking commandButton, but it always returns null instead of inputText value. What's the problem in my codes. Someone, helps...
Thanks in advance..
Here username is the property of UserBean.java class. As a result, you must have to call the username variable through a object of the parent(UserBean.java) class.So, try it, mbean.getUsername() instead of only username.
I am trying to create a basic datatable which fetches the value from database and displays in the table format. However while I try to debug I see that managed bean functions are not being called. Below is the code
list.xhtml:
<h:body>
<h3>Expense list</h3>
<h:dataTable value="#{userMB.entries}" var="e" styleClass="table"
headerClass="table-header" rowClasses="table-odd-row,table-even-row">
<h:column>
<f:facet name="header">Date</f:facet>
#{e.date}
</h:column>
</h:dataTable>
</h:body>
UserMB.java
#ManagedBean
#SessionScoped
public class UserMB {
private List<Entry> entries;
#EJB(mappedName = "entryServices")
private EntryServices entryServices;
public UserMB() {
}
#PostConstruct
public void init() {
FacesContext context = FacesContext.getCurrentInstance();
HttpServletRequest request = (HttpServletRequest) context
.getExternalContext().getRequest();
HttpSession httpSession = request.getSession(false);
User user = (User) httpSession.getAttribute("user");
entries = new ArrayList<Entry>();
entries = entryServices.getEntryByUser(user);
}
public List<Entry> getEntries() {
return entries;
}
public void setEntries(List<Entry> entries) {
this.entries = entries;
}
public EntryServices getEntryServices() {
return entryServices;
}
public void setEntryServices(
EntryServices entryServices) {
this.entryServices = entryServices;
}
}
I don't see any error in the code or the facelet, sometimes I not choose the right package for the annotation that must be javax.faces.ManagedBean and javax.faces.SessionScoped otherwise the bean is never created.
In glassfish when I use a EJB in the ManagedBean it need to be serialized could you try this.
I hope this could help you.
This is my problem.
Change the imports and works:
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
This question already has answers here:
Pick Custom Object from Select one menu JSF [duplicate]
(2 answers)
Closed 9 years ago.
i want to pick custom object from select one menu. it neither shows an error nor values. what to do? please help me. thanks in advance.
Now i'm seeing Null pointer exception at getAsObject at this line:
return getCurrencyService().getCurrencyBtId(currencyId);
this is my xhtml document
<h:panelGrid columns="2">
<p:outputLabel value="" />
<p:selectOneMenu id="CurrencyMenu" value="#{CurrencyMB.currency}" converter="currencyConverter" >
<f:selectItems value="#{CurrencyMB.currencyList}" var="currency" itemValue="#{currency}" itemLabel="#{currency.currencyName}" >
</f:selectItems>
<p:ajax update="currencyOut" />
</p:selectOneMenu>
<p:outputLabel value="Currency Id : #{CurrencyMB.currency.currencyId}" id="currencyOut" />
</h:panelGrid>
this is my managedBean class.
#ManagedBean(name = "CurrencyMB")
#RequestScoped
public class CurrencyManagedBean implements Serializable{
private Currency currency;
private List<Currency> currencyList;
public Currency getCurrency() {
return currency;
}
public void setCurrency(Currency currency) {
this.currency = currency;
}
public List<Currency> getCurrencyList() {
currencyList = new ArrayList<Currency>();
currencyList.addAll(getiCurrencyService().getCurrencies());
return currencyList;
}
public void setCurrencyList(List<Currency> currencyList) {
this.currencyList = currencyList;
}
}
this is my currencyConverter class code:
**#FacesConverter("currencyConverter")
public class CurrencyConverter implements Converter {
#ManagedProperty(value = "#{currencyService}")
private ICurrencyService currencyService;
public ICurrencyService getCurrencyService() {
return currencyService;
}
public void setCurrencyService(ICurrencyService currencyService) {
this.currencyService = currencyService;
}
#Override
public Object getAsObject(FacesContext arg0, UIComponent arg1, String value) {
int currencyId = Integer.valueOf(value);
return getCurrencyService().getCurrencyBtId(currencyId);
}
#Override
public String getAsString(FacesContext arg0, UIComponent arg1, Object value) {
Currency currency = (Currency) value;
int currencyId = currency.getCurrencyId();
return String.valueOf(currencyId);
}
}**
As it can be seen in many questions, and their answers, here, #FacesConverter is not eligible for injection. In your case, you try to inject your service via #ManagedProperty, which yields NPE, as Luiggi told you in a comment to your initial question.
With the current JSF release, all you can do to inject services in your converters is to give up using #FacesConverter and switch to using standard #ManagedBean annotation, thus referring to your converter not by id, but by bean name, like in converter="#{currencyConverter}".
I am using the following piece of code in my JSF 2.0 with RichFaces 4.0. I have a managed bean that has an enum. Now i want to assign the value of the enum via an ActionParam. How can I do this? Here is the code:
<a4j:commandLink id="pendingTransactions"
action="#{tellerBean.getPendingTransactions}" value="Show Pending"
styleClass="button category-btn">
<a4j:actionparam name="first" value=""
assignTo="" />
</a4j:commandLink>
and my managed bean:
#ManagedBean
#SessionScoped
public class TellerBean implements Serializable{
public enum TransactionType {
PENDING,PROCESSED,ALL
}
private static final long serialVersionUID = -321111;
private String recipientID;
private String recipientName;
private String transactionAmount;
private TransactionType transactionType;
public String getRecipientID() {
return recipientID;
}
public void setRecipientID(String recipientID) {
this.recipientID = recipientID;
}
public String getRecipientName() {
return recipientName;
}
public void setRecipientName(String recipientName) {
this.recipientName = recipientName;
}
public String getTransactionAmount() {
return transactionAmount;
}
public void setTransactionAmount(String transactionAmount) {
this.transactionAmount = transactionAmount;
}
public void searchTransactions() {}
public TransactionType getTransactionType() {
return transactionType;
}
public void setTransactionType(TransactionType transactionType) {
this.transactionType = transactionType;
}
public void getTransactions() {}
}
Now I want to assign the value of the transactionType variable to an Enum value. How can I do this?
I don't know what you want to do with the variable or how you want to display it, so here's a generic example.
First of all, the JSF page must be able to 'iterate' over the enum to discover the possible values. I'm using h:selectOneMenu as an example which is filled using f:selectItems. f:selectItems expects a List<> as input so we need to create a method in the TellerBean:
public List<TransactionType> getTransactionTypes()
{
List<TransactionTypes> tt = new ArrayList<TransactionType>();
for (TransactionType t : TransactionType.values())
{
tt.add(new TransactionType(t, t.toString()))
}
return tt;
}
Then for an example JSF page:
<h:form>
<h:selectOneMenu value="#{tellerBean.transactionType}">
<f:selectItems value="#{tellerBean.transactionTypes}"/>
</h:selectOneMenu>
<h:commandButton value="Submit" action="#{tellerBean.someMethod}"/>
</h:form>
The JSF page should display a drop-down list with the values of the enum. When clicking the button labeled "Submit" it executes someMethod() in TellerBean. Of course this doesn't work because the method doesn't exist, but it's just an example. ;-)