passing parameter from one page to another page in JSF - jsf-2

i am little bit stuck in my problem. i have sent the parameter from one xhtml page to another xhtml page successfully and i printed that parameter on my next page xhtml like this, #{param['id']}, but the problem is my #postConstructor is not executing, because i want that whenever my next page loads the parameter id sends over to database and get the required details in my datatable.
here is my code snippet of xhtml page from where i am sending parameters
<h:column>
<f:facet name="header">
Title
</f:facet>
<h:link value="#{item.title}" outcome="showObj.xhtml">
<f:param name="pid" value="#{item.id}" />
</h:link>
</h:column>
and here is my managedBean
package mb;
import java.io.Serializable;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
#ManagedBean(name="next")
#RequestScoped
public class showObj implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#ManagedProperty(value="#{param.pid}")
private String name;
public String getName() {
System.out.println("in getter"+name);
return name;
}
public void setName(String name) {
this.name = name;
}
#PostConstruct // this will execute init() after id is injected
public void init() {
System.out.println("in init");
}
}
and here is my next xhtml page content, where i am receiving parameters.
<h:outputText value="#{param['pid']}"></h:outputText>
now i want that whenever my this parameter is received here, on page loading this parameter should send to database (the other ejb project). i know that if my #postConstructor runs than i can achieve this thing. but my #postConstructor is not executing.
i have also searched my problem over internet, they all says something about mojarra version, so i let you know that i have 2.1.6 version

Related

Why can't I set f:selectItems in encodeBegin in composite component?

I'm trying to understand how to program composite components, and have followed the great example by balusc, and others, but I'm missing something.
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui"
xmlns:c="http://java.sun.com/jstl/core"
xmlns:cc="http://java.sun.com/jsf/composite">
<cc:interface componentType="simpleComponent">
<cc:attribute name="value" required="true" type="example.LanguageDefinition"/>
<cc:attribute name="possibilities" default="de_DE" type="java.lang.String"/>
</cc:interface>
<cc:implementation>
<p:selectOneMenu binding="#{cc.inputComponent}" converter="omnifaces.SelectItemsConverter" var="l"
value="#{cc.attrs.value}">
<p:ajax update="#form"/>
<f:selectItems value="#{cc.languages}" var="l" itemLabel="#{l.label}"
itemValue="#{l}" />
<p:column>#{l.label}</p:column>
<p:column>
<p:graphicImage name="#{l.imgPath}" />
</p:column>
</p:selectOneMenu>
</cc:implementation>
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.faces.component.FacesComponent;
import javax.faces.component.NamingContainer;
import javax.faces.component.UIInput;
import javax.faces.component.UINamingContainer;
import javax.faces.context.FacesContext;
import example.LanguageDefinition;
#FacesComponent("simpleComponent")
public class SimpleComponent extends UIInput implements NamingContainer {
private UIInput inputComponent;
public UIInput getInputComponent() {
return inputComponent;
}
public void setInputComponent(UIInput inputComponent) {
this.inputComponent = inputComponent;
}
#Override
public Object getSubmittedValue() {
return inputComponent.getSubmittedValue();
}
#Override
protected Object getConvertedValue(FacesContext context, Object newSubmittedValue) {
return (String) newSubmittedValue;
}
#Override
public String getFamily() {
return UINamingContainer.COMPONENT_FAMILY;
}
#Override
public void encodeBegin(FacesContext context) throws IOException {
String possibilities = getAttributeValue("possibilities", "en_US");
// In theory, build based on incoming possibilities, now hard code
List<LanguageDefinition> languages = new ArrayList<LanguageDefinition>();
languages.add(new LanguageDefinition("pt_PT",
"images/flags/PT.gif", "Português (Portugal)"));
languages.add(new LanguageDefinition("cs_CZ",
"images/flags/CZ.gif", "Czech (Czech Republic)"));
getStateHelper().put("languages", languages);
super.encodeBegin(context);
}
#SuppressWarnings("unchecked")
public List<LanguageDefinition> getLanguages() {
return (List<LanguageDefinition>) getStateHelper().get("languages");
}
/**
* Return specified attribute value or otherwise the specified default if it's null.
*/
#SuppressWarnings("unchecked")
private <T> T getAttributeValue(String key, T defaultValue) {
T value = (T) getAttributes().get(key);
return (value != null) ? value : defaultValue;
}
}
This isn't working calling like this:
<ex:simpleComponent value="#{compBean.selected}"/>
Everything renders fine, but the submitted value is never passed back to my "compBean". However, if I set the selectItems "languages" in any other way other than doing it in encodeBegin it works... as a member variable with getters and setters, or using this code:
<c:set target="#{cc}" property="possibilities" value="#{cc.attrs.possibilities}"/>
In combination with this much simpler class:
import java.util.ArrayList;
import java.util.List;
import javax.faces.component.FacesComponent;
import javax.faces.component.NamingContainer;
import javax.faces.component.UIInput;
import javax.faces.component.UINamingContainer;
import example.LanguageDefinition;
#FacesComponent("simpleComponent")
public class SimpleComponent extends UIInput implements NamingContainer {
#Override
public String getFamily() {
return UINamingContainer.COMPONENT_FAMILY;
}
public void setPossibilities(String possibilities) {
if (getStateHelper().get("possibilities") == null) {
List<LanguageDefinition> languages = new ArrayList<LanguageDefinition>();
languages.add(new LanguageDefinition("pt_PT",
"images/flags/PT.gif", "Português (Portugal)"));
languages.add(new LanguageDefinition("cs_CZ",
"images/flags/CZ.gif", "Czech (Czech Republic)"));
getStateHelper().put("languages", languages);
getStateHelper().put("possibilities", possibilities);
}
}
public String getPossibilities() {
return (String) getStateHelper().get("possibilities");
}
#SuppressWarnings("unchecked")
public List<LanguageDefinition> getLanguages() {
return (List<LanguageDefinition>) getStateHelper().get("languages");
}
}
But, it doesn't seem right to do it this way (wasn't the way balusc did it), so I'm just trying to understand. Which way is better? Assuming the first, why is mine not working?
Thanks!
So... the reason this wasn't working was because I forgot to implement Serializable on my custom drop down list value object "example.LanguageDefinition".
Hopefully the next person won't have to look for this needle in the haystack as long as I did :)

JSF correct use of dependency

JSF 2.1
Tomcat 7.0
Is this a wrong use of dependency injection?
It works ok moving around the page. But "it works" is not the same as "it's correct".
I would use this pattern also for search purpose. I have a request and i like to use it to populate a table in the same page. Is this possible?
index.xhtml
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<link rel="SHORTCUT ICON" href= "resources/img/onlyT.ico"></link>
<title>title</title>
<h:outputStylesheet library="css" name="compass.css"/>
</h:head>
<h:body>
Login system
<br />
<h:form>
User : <h:inputText value="#{user.username}" />
Password : <h:inputSecret value="#{user.password}" />
<h:commandButton action="#{loginBean.performLogin()}" value="Submit" />
<h:commandButton value="reset" type="reset" />
<h:commandButton value="ChangePsW" action="changePassword"></h:commandButton>
</h:form>
<h:message for="" style="color:red;margin:8px;"/>
</h:body>
</html>
LoginBan.java
#ManagedBean
#RequestScoped
public class LoginBean {
#ManagedProperty(value="#{user}")
private UserBean userBean;
//must povide the setter method
public void setUserBean(UserBean userBean) {
this.userBean = userBean;
}
public LoginBean() {}
public String performLogin(){
//Mi connetto al db
if(userBean.getUsername().equalsIgnoreCase( "mario")){
//effettuo i controlli per stabilire se esiste l'utente
userBean.setRoles("-EE-E-E-E-E-E");
return "/mainPortal/mainPortal";
}
return "/mainPortal/index";
}
}
UserBean.java
#ManagedBean (name="user")
#SessionScoped
public class UserBean implements Serializable {
private String Username;
private String Password;
private String Roles;
/** Creates a new instance of UserBean */
public UserBean() {
}
/**
* #return the Username
*/
public String getUsername() {
return Username;
}
/**
* #param Username the Username to set
*/
public void setUsername( String Username ) {
this.Username = Username;
}
/**
* #return the Password
*/
public String getPassword() {
return Password;
}
/**
* #return the Roles
*/
public String getRoles() {
return Roles;
}
/**
* #param Roles the Roles to set
*/
public void setRoles( String Roles ) {
this.Roles = Roles;
}
/**
* #param Password the Password to set
*/
public void setPassword( String Password ) {
this.Password = Password;
}
change password also use the userBean and has his changePasswordBean.
JSF 2 allows you injecting managed beans in other managed beans. This is only limited by the scope of the bean you're actually injecting, which has to be greater than the scope of the bean you actually are in. I mean, you can inject #SessionScoped bean in a #ViewScoped one, but not in the other way. As you follow that convention, I think you're doing it well.
Generally, your application should be composed by #ViewScoped or #RequestScoped beans to handle current user input/outputs and wider scoped beans for session or application means. So, when user logs in, it's a good idea to maintain his data in a session context, however I suggest you not to maintain user's password into session, at least if you're not going to use it once the login has been succesfully done.
Finally the question you make about search requests, I think you can implement a search input in your page and make your result table load dinamically depending on the search. Just use ajax to obtain it without having to reload the whole page. You can implement everything in a #ViewScoped bean, but remember not to return navigation results in your listener methods if you want to maintain the bean working.

javax.el.PropertyNotFoundException:Property not found on type java.io.File in primefaces download

I am using Primefaces 3.2 and developing the file download functionality and I am getting list of file names from my local which i wanted to display them in jsf datatable with clickable option(h:commandlink).
When I excute my Code I am getting following exception.
javax.el.PropertyNotFoundException: /faces/fileDownload.xhtml at line
33 and column 115 value="#{x.fileName}": Property 'fileName' not found
on type java.io.File
My Code looks like this Java File
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
#ManagedBean(name="fileDownloadController")
#SessionScoped
public class FileDownloadController {
private StreamedContent file;
private List<File> listfiles=new ArrayList<File>();
private String fileName;
public FileDownloadController() {
File filestream=new File("C:/temp.pdf");
InputStream stream=null;
try {
stream = new FileInputStream(filestream);
file = new DefaultStreamedContent(stream, "application/pdf", "temp.pdf");
stream.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public List<File> getListfiles() {
File folder = new File("c:\\");
File[] listOfFiles = folder.listFiles();
listfiles=Arrays.asList(listOfFiles);
int i;
for(i=0;i<listfiles.size();i++){
System.out.println("The List of file are"+listfiles.get(i));
listfiles.get(i);
}
return listfiles;
}
public void setListfiles(List<File> listfiles) {
this.listfiles = listfiles;
}
public String getFileName() {
getListfiles();
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public StreamedContent getFile() {
return this. file;
}
}
My XHTML looks like this.
<h:form id="form">
<h:dataTable value="#{fileDownloadController.listfiles}" var="x"
bgcolor="#F1F1F1" border="10" cellpadding="5"
cellspacing="3" first="0" rows="4" width="50%"
summary="This is a JSF code to create dataTable.">
<h:column>
<f:facet name="header">
<h:outputText value="File Names"></h:outputText>
</f:facet>
<h:commandLink value="#{x.fileName}" onclick="PrimeFaces.monitorDownload(showStatus, hideStatus)">
<p:fileDownload value="#{fileDownloadController.file}" />
</h:commandLink>
</h:column>
</h:dataTable>
</h:form>
I am not able to figure out where i went Wrong.Please help me.
How did you come to using #{x.fileName}? Look carefully in the javadoc of the java.io.File class. Right, there's no such method like getFileName(). That's exactly what the exception is trying to tell you.
value="#{x.fileName}": Property 'fileName' not found on type java.io.File
Most likely you meant to use the getName() method instead.
#{x.name}
Unrelated to the concrete problem, your code would be more self-documenting if you used var="file" instead of the nonsensicial var="x".

SFSB being removed

I'm using JBoss6.1.Final, JSF 2.0 (Mojarra), Weld CDI, MyFaces CODI 1.0.5 (for view-access-scoped)
I'm using something like the Gateway Pattern from Real World Java EE Patterns Rethinking Best Practices (unfortunately I don't have it with me, so I may have screwed something up here). Basically, the application allows a user to go into "edit mode" and edit a List of people (create, edit, remove) maintained in a #ViewAccessScoped backing bean with an extended persistence context and then click a "save" command link that flushes all their changes to the database. At first I was having a problem with ViewExpiredExceptions (if the browser was idle past the session-timeout period and then further requests are performed), but I added some jQuery to make a get request to a servlet that keeps the session alive (called 10 seconds before session-timeout). This seems to be working but now I have another problem, the backing bean is also a SFSB and after some idle time, it is being removed resulting in the following error message being logged (and all ajax rendered data disappears) when I attempt to perform more edits ...
13:06:22,063 SEVERE [javax.enterprise.resource.webcontainer.jsf.context] javax.el.ELException: /index.xhtml #27,81 rendered="#{!conversationBean.editMode}": javax.ejb.NoSuchEJBException: Could not find stateful bean: 43h1h2f-9c7qkb-h34t0f34-1-h34teo9p-de
Any ideas on how I could prevent SFSB removal or at least handle it more gracefully?
Here's my backing bean:
package com.ray.named;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJBTransactionRolledbackException;
import javax.ejb.Stateful;
import javax.ejb.TransactionAttribute;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;
import org.apache.myfaces.extensions.cdi.core.api.scope.conversation.ViewAccessScoped;
import com.ray.model.Person;
#Named
#Stateful
#ViewAccessScoped
#TransactionAttribute(javax.ejb.TransactionAttributeType.NEVER)
public class ConversationBean implements Serializable {
private static final long serialVersionUID = 1L;
//properties
private List<Person> people;
private String name;
private Boolean editMode;
#PersistenceContext(type=PersistenceContextType.EXTENDED)
private EntityManager em;
#PostConstruct
public void init() {
people = em.createNamedQuery("Person.findAll", Person.class).getResultList();
setEditMode(false);
}
//event listeners
public void beginEdits() {
setEditMode(true);
}
public void addPerson() {
Person p = new Person(name);
em.persist(p);
people.add(p);
name = null;
}
public void removePerson(Person p) {
people.remove(people.indexOf(p));
em.remove(p);
}
//this method flushes the persistence context to the database
#TransactionAttribute(javax.ejb.TransactionAttributeType.REQUIRES_NEW)
public void saveEdits() {
setEditMode(false);
}
//getters/setters
public List<Person> getPeople() {
return people;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Boolean getEditMode() {
return editMode;
}
public void setEditMode(Boolean editMode) {
this.editMode = editMode;
}
}
Here's the Person entity bean:
package com.ray.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Version;
#Entity
#NamedQueries({
#NamedQuery(name="Person.findAll",
query="SELECT p FROM Person p")
})
public class Person {
#Id #GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
private String name;
#Version
private int version;
public Person() { }
public Person(String name) {
setName(name);
}
public boolean equals(Object o) {
if (!(o instanceof Person)) {
return false;
}
return id == ((Person)o).id;
}
//getters/setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getId() {
return id;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
}
Here's the view:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
setInterval(function() {
$.get("#{request.contextPath}/poll");
}, #{(session.maxInactiveInterval - 10) * 1000});
});
</script>
<title>Conversation Test</title>
</h:head>
<h:body>
<h:form>
<h:commandLink value="Begin Edits" rendered="#{!conversationBean.editMode}">
<f:ajax render="#form" listener="#{conversationBean.beginEdits}"/>
</h:commandLink>
<h:commandLink value="Save" rendered="#{conversationBean.editMode}">
<f:ajax render="#form" listener="#{conversationBean.saveEdits}"/>
</h:commandLink>
<h:dataTable id="peopleTable" value="#{conversationBean.people}" var="person">
<h:column>
<f:facet name="header">Name</f:facet>
<h:panelGroup>
<h:inputText value="#{person.name}" disabled="#{!conversationBean.editMode}">
<f:ajax/>
</h:inputText>
<h:commandLink value="X" disabled="#{!conversationBean.editMode}">
<f:ajax render="#form" listener="#{conversationBean.removePerson(person)}"/>
</h:commandLink>
</h:panelGroup>
</h:column>
</h:dataTable>
<h:panelGrid columns="2">
<h:outputLabel for="name">Name:</h:outputLabel>
<h:inputText id="name" value="#{conversationBean.name}" disabled="#{!conversationBean.editMode}"/>
</h:panelGrid>
<h:commandButton value="Add" disabled="#{!conversationBean.editMode}">
<f:ajax execute="#form" render="#form" listener="#{conversationBean.addPerson}"/>
</h:commandButton>
</h:form>
</h:body>
</html>
Here's a servlet used to keep the session alive (called by jQuery ajax get request 10 seconds before session expires):
package com.ray.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class PollServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void init() throws ServletException {
}
public String getServletInfo() {
return null;
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
request.getSession(); //Keep session alive
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
}
public void destroy() {
}
}
Any ideas on how I could prevent SFSB removal or at least handle it
more gracefully?
To investigate further I would recommend to take a look at the EJB lifecycle hooks for passivation and add some debug output there.
Should that be the source of the problem you will be able to configure / deactivate passivation - but scalability might come up as an issue.
Honestly, this scenario seems quite uncommon to me. In general I would expect requests / conversations / sessions to be working more or less in the default boundaries - should you find yourself writing code that circumvents this can it be that you are better off with a RESTful / stateless approach...?
Please update the question with further information if available.
I suppose you have already solved your problem. Otherwise, this JBoss wiki page should be helpful (also for future readers...).
https://community.jboss.org/wiki/Ejb3DisableSfsbPassivation
Cheers,
Luigi

Primefaces inplace events not fired inside datatable

I'm using jsf 2.0, primefaces 3.0M3 and jboss 6.0.0 in a project. I'm trying to make a table cell editable as in primefaces showcase, but the events to save and cancel didn't get fired. So, I decided to try and make only one field editable inside the datable with an inplace element and use the save event. It didn't work also. The code is as follow:
<ui:define name="search_results">
<h:form id="search_results">
<p:dataTable id="tbl" var="amb" value="#{environment.searchResult}">
<p:column id="firstcolumn">
<f:facet id="nameFct" name="header">#{label['menu.admin.environment']}</f:facet>
<p:inplace editor="true" effectSpeed="fast" event="dblclick">
<p:inputText value="#{amb.dsAmbiente}" />
<p:ajax event="save" listener="#{environment.update(amb)}" />
</p:inplace>
</p:column>
</p:dataTable>
</h:form>
</ui:define>
and the class that is called in the listener
#Named("environment")
#ViewScoped
public class Environment extends AbstractBean implements Serializable{
private static final long serialVersionUID = 1L;
private AmbienteRemote environmentRemote;
private List<Empresa> companies;
private Ambiente env;
#Inject
private transient FacesContext context;
#Inject
private transient Messages messages;
private String compSearch;
private String envSearch;
private EnumFlStatusAmbiente statusSearch;
private List<Ambiente> searchResult;
public Environment()
{
}
//....
public String update(final Ambiente amb)
{
System.out.println("update");
return null;
}
//....
}
Can anybody help?
Thanks
Kelly
CDI components (annotated with #Named) does not have #ViewScoped.
You can't mix JSF Managed Beans imports with CDI imports.
Try to use sessionScope (remember - class have to implements Serializable).
(ps: Probably you will use wrong import such as
import javax.faces.bean.SessionScoped;
instead
import javax.enterprise.context.SessionScoped;)

Resources