keep getting javax.faces.application.ViewExpiredException: viewId with jsf 2 [duplicate] - jsf-2

This question already has answers here:
javax.faces.application.ViewExpiredException: View could not be restored
(11 answers)
Closed 7 years ago.
Whatever I do I get javax.faces.application.ViewExpiredException: viewId. I know how to handle the exception (redirect to the main page again if I get the error), the issue is that any action I call from a commandButton is not executed.
Basically I have a simple view with a commandButton with an action.. I press it and I get the viewExpiredException or if I handle the error, I don't get the error messages but still my commandButton does not work.
I tried adding this:
<context-param>
<param-name>javax.faces.PARTIAL_STATE_SAVING</param-name>
<param-value>client</param-value>
</context-param>
but it doesn't work. I don't know what is going on..
This is my 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"
lang="es">
<div class="container">
<h:form id="principal">
<h1>Sistema de carga de publicaciones</h1>
<h:outputText value="Ingrese el año por el que desea buscar publicaciones" />
<h:inputText
id="year"
value="#{publicaciones.año}" />
<h:commandButton
style="display:block"
id="boton-codigo-facultad"
value="Buscar"
type="submit">
</h:commandButton>
<h:panelGroup id="output">
<h:outputText
style="display:block"
value="Total publicaciones en la DB:#{publicaciones.totalPublicacionesDB}" />
<h:outputText
style="display:block"
value="Publicaciones obtenidas desde el WS:" />
<h:outputText
style="display:block"
value="Publicaciones nuevas:" />
</h:panelGroup>
<h:commandButton
style="display:block"
id="insertar"
value="Cargar publicacion"
action="#{insert.insertPublicacionDB}">
</h:commandButton>
</h:form>
</div>
</html>
backing bean:
#ManagedBean(name="insert")
#ViewScoped
public class comparaDatosBean implements Serializable {
private static final long serialVersionUID = 1L;
Map<String, Object> parametros=new HashMap<String, Object>();
Map<String, Object> params2=new HashMap<String, Object>();
#PostConstruct
public void init(){
System.out.println("pase por aqui!!");
}
public void insertPublicacionDB() throws SQLException {
ApplicationContext applicationContext = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
ControllerPublicacion controlador= (ControllerPublicacion) applicationContext.getBean("controllerPublicaciones");
parametros.put("ut","234567876545555");
parametros.put("py", 2013);
params2.put("ut", "234567876545555");
params2.put("bp","asjñldfkjsñd");
params2.put("la", "Español");
params2.put("ti","Publicacion de prueba");
params2.put("py",2013);
params2.put("sn", "234wf");
params2.put("di", "asdfsf");
params2.put("j9", "");
params2.put("dt", "");
params2.put("ga", "");
params2.put("dt", "");
params2.put("so", "");
params2.put("fx", "");
params2.put("ep", "");
params2.put("issue", "");
params2.put("parte","");
params2.put("vl", "");
params2.put("rp", "");
params2.put("vinculada", null);
params2.put("ji", "");
params2.put("pd","");
params2.put("pg", "");
params2.put("pa","");
params2.put("ab","");
params2.put("pi", "");
params2.put("numero_articulo", null);
params2.put("tipo_carga_revista",null);
params2.put("id",null );
params2.put("su", "");
System.out.println(params2.get("la"));
if(controlador.existeEnDB(parametros)>0){
System.out.println("La publicacion ya existe en la Base de Datos");
} else {
controlador.insertPublicacion(params2);
System.out.println("la publicacion ha sido añadida");
}
}
public Map<String, Object> getParametros() {
return parametros;
}
public void setParametros(Map<String, Object> parametros) {
this.parametros = parametros;
}
public Map<String, Object> getParams2() {
return params2;
}
public void setParams2(Map<String, Object> params2) {
this.params2 = params2;
}
}
Error message:
GRAVE: Servlet.service() for servlet [Faces Servlet] in context with path [/test] threw exception [viewId:/main.jsf - No se pudo restablecer la vista /main.jsf.] with root cause
javax.faces.application.ViewExpiredException: viewId:/main.jsf - No se pudo restablecer la vista /main.jsf.
at com.sun.faces.lifecycle.RestoreViewPhase.execute(RestoreViewPhase.java:212)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.RestoreViewPhase.doPhase(RestoreViewPhase.java:110)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:312)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.shiro.web.servlet.AbstractShiroFilter.executeChain(AbstractShiroFilter.java:449)
at org.apache.shiro.web.servlet.AbstractShiroFilter$1.call(AbstractShiroFilter.java:365)
at org.apache.shiro.subject.support.SubjectCallable.doCall(SubjectCallable.java:90)
at org.apache.shiro.subject.support.SubjectCallable.call(SubjectCallable.java:83)
at org.apache.shiro.subject.support.DelegatingSubject.execute(DelegatingSubject.java:383)
at org.apache.shiro.web.servlet.AbstractShiroFilter.doFilterInternal(AbstractShiroFilter.java:362)
at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1002)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)
What I need is to know why this is happening, not how to handle the exception.. I can't call any action from a commandButton because nothing happens.

I solved it with this:
<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>client</param-value>
</context-param>
In some places I saw it like this javax.faces.PARTIAL_STATE_SAVING but it did not work.

Related

Timeout via idlemonitor (primefaces) does not work

i want to use the idle monitor of primefaces for the session timeout.
Properly it works. But the redirect to my login-page (login.xhtml it doesn't work.
I use this the idle-monitor in my body of the template of my xhtml pages:
Template.xhtml
<p:idleMonitor timeout="1800000" >
<p:ajax event="idle" listener="#{pageServiceBean.timeout()}" oncomplete="alert('Die Session ist abgelaufen.')"/>
</p:idleMonitor>
The code of the pageServiceBean is:
PageServiceBean.xhtml
#ManagedBean
#SessionScoped
/**Die Page-Service Bean wird in der Fußzeile der Seite eingesetzt und beinhaltet den Zurück-Button bzw. den Logout Button*/
public class PageServiceBean implements Serializable{
/**
*
*/
private static final long serialVersionUID = 3251724422690388588L;
/**Leitet auf zur Auswahlseite zurück*/
public String cancel(){
return"/sampleForDB.xhtml";
}
/**Leitet zur Loginseite zurück*/
public String cancelSampleButton(){
return"/login.xhtml";
}
public void timeout() throws IOException {
FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
FacesContext.getCurrentInstance().getExternalContext().redirect("...login.xhtml");
}
}
I have no redirect to the login.xhtml. But the user ist logged out. So the stuff is not valid any more. The to other function (cancel and cancelSampleButton) works. So they navigate to the correct page.
I looked at the answer from Answer in another post But that don't fixed my problem.
In this post the person speaks to set the time in the web.xml. But i don't no which code did i write in the xhtml.
And i don't know what does the three dots in the redirect method do FacesContext.getCurrentInstance().getExternalContext().redirect("...login.xhtml");
Any idea?
I found a solution.
in the xhtml-page PrimefacsIdleMonitor.xhtml:
<!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:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head></h:head>
<body>
<h:form>
<p:growl id="msg" showDetail="true" sticky="true" />
<!-- nach 10 Sekunden wird der idelDialog gestartet -->
<p:idleMonitor timeout="10000" onidle="idleDialog.show()" />
<p:confirmDialog id="confirmDialog"
message="Die Session ist abgelaufen. Bitte klicke auf Ok um weiter zu arbeiten."
header="Session ist abgelaufen" severity="alert" widgetVar="idleDialog">
<p:commandButton id="confirm" value="Ok" update="msg"
oncomplete="idleDialog.hide()"
actionListener="#{pageServiceBean.welcomeListener}" />
<p:commandButton id="Logout" value="Abmelden" update="msg"
oncomplete="idleDialog.hide()"
actionListener="#{pageServiceBean.logoutListener}" />
</p:confirmDialog>
</h:form>
</body>
</html>
In any xhtml page where the idle-monitor is used:
<div id="idle">
<div id="id">
<ui:insert name="idle">
<ui:include src="/META-INF/templates/PrimefacesIdleMonitor.xhtml"/>
</ui:insert>
</div>
</div>
In the PageServiceBean.java
public void welcomeListener() {
FacesContext.getCurrentInstance().addMessage(
null,
new FacesMessage(FacesMessage.SEVERITY_WARN, "Hallo",
"Du bist wieder eingeloggt."));
}
public void logoutListener() throws IOException {
FacesContext.getCurrentInstance().addMessage(
null,
new FacesMessage(FacesMessage.SEVERITY_WARN,
"Du bist ausgeloggt!", "Bis dann"));
FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
ExternalContext ec =FacesContext.getCurrentInstance().getExternalContext();
System.out.println(ec.getRequestContextPath()+"/login.xhtml");
ec.redirect(ec.getRequestContextPath()+"/login.xhtml");
FacesMessage msg = new FacesMessage("Information ", " Die Session ist abgelaufen. Bitte melden sie sich erneut an.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
If the user klick "ok" he can work again. If he klick logout he will be redirect to the login-back. No error or something else is throw.

Null Pointer Exception while calling a bean method (PrimesFaces)

the problem is that when i use my command button i have a NPE and i dont why there is some code and a stacktrace of the exception i hope you will help because i have spend a day and still dont know why (primefaces 4.0 ) JSF 2.1.6
javax.faces.el.EvaluationException: javax.el.ELException: /test.xhtml at line 54 and column 113 action="#{messageBean.save}": java.lang.NullPointerException
at javax.faces.component._MethodExpressionToMethodBinding.invoke(_MethodExpressionToMethodBinding.java:96)
at org.apache.myfaces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:100)
at javax.faces.component.UICommand.broadcast(UICommand.java:120)
at javax.faces.component.UIViewRoot._broadcastAll(UIViewRoot.java:937)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:271)
at javax.faces.component.UIViewRoot._process(UIViewRoot.java:1249)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:675)
at org.apache.myfaces.lifecycle.InvokeApplicationExecutor.execute(InvokeApplicationExecutor.java:34)
at org.apache.myfaces.lifecycle.LifecycleImpl.executePhase(LifecycleImpl.java:171)
at org.apache.myfaces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:189)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:315)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: javax.el.ELException: /test.xhtml at line 54 and column 113 action="#{messageBean.save}": java.lang.NullPointerException
at org.apache.myfaces.view.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:95)
at javax.faces.component._MethodExpressionToMethodBinding.invoke(_MethodExpressionToMethodBinding.java:88)
... 29 more
Caused by: java.lang.NullPointerException
at ma.corporate.bean.MessageBean.save(MessageBean.java:60)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.el.parser.AstValue.invoke(AstValue.java:278)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:273)
at org.apache.myfaces.view.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:83)
... 30 more
My Page
<!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:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head></h:head>
<h:body>
<p:panel header="Contactez Nous">
<p:growl id="message" showDetail="true"/>
<h:form id="form">
<p:panelGrid style="width:700px;" styleClass="contactcss"
columns="2">
<p:inputText value="#{messageBean.message.nomComplet}" style="width:600px" id="nom" required="true"
requiredMessage="Champs Obligatoire">
<p:watermark for="nom" value="Nom" />
</p:inputText>
<p:message for="nom" display="both" />
<p:inputText style="width:600px" value="#{messageBean.message.email}" id="email" required="true"
requiredMessage="Champ Obligatoire"
validatorMessage="Email Invalide">
<p:watermark for="email" value="Email" />
<f:validateRegex
pattern="^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*#[A-Za-z0-9-]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$" />
</p:inputText>
<p:message for="email" display="both" />
<p:inputText style="width:600px" value="#{messageBean.message.objet}" id="objet" required="true"
requiredMessage="Champ Obligatoire">
<p:watermark for="objet" value="Objet" />
</p:inputText>
<p:message for="objet" display="both" />
<p:inputMask mask="9999-999-999" style="width:600px" value="#{messageBean.message.telephone}" id="telephone">
<p:watermark for="telephone" value="téléphone" />
</p:inputMask>
<p:message for="telephone" display="both" />
<p:inputTextarea style="width:600px;height:200px" value="#{messageBean.message.textMessage}" id="message"
required="true" requiredMessage="Champ Obligatoire">
<p:watermark for="message" value="Message" />
</p:inputTextarea>
<p:message for="message" display="both" />
<p:commandButton update=":form :message" style="float:right;" action="#{messageBean.save}" value="Envoyer"></p:commandButton>
</p:panelGrid>
</h:form>
</p:panel>
</h:body>
</html>
My Bean
package ma.corporate.bean;
import java.io.Serializable;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import ma.corporate.facade.MessageFacade;
import ma.corporate.model.Message;
import ma.corporate.util.Email;
import ma.corporate.util.EmailSender;
import org.primefaces.context.RequestContext;
#ManagedBean(name = "messageBean")
#SessionScoped
public class MessageBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private MessageFacade messageFacade;
private List<Message> messages;
private Message message;
private Email email =new Email();
private String reponse;
public MessageBean() {
message = new Message();
}
public List<Message> getMessages() {
// messages = messageFacade.Lister();
messageFacade = new MessageFacade();
messages = messageFacade.Lister();
return messages;
}
public void setMessages(List<Message> messages) {
this.messages = messages;
}
public Message getMessage() {
return message;
}
public void setMessage(Message message) {
this.message = message;
}
public void save() {
System.out.println(message.getEmail());
System.out.println(message.getNomComplet());
System.out.println(message.getObjet());
System.out.println(message.getTelephone());
System.out.println(message.getTextMessage());
messageFacade.enregistrer(message);
}
public void Supprimer(Message message) {
messageFacade.supprimer(message);
messages = messageFacade.Lister();
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Succès","Suppression Complète"));
}
public void init(Message message) {
this.message = message;
email.setDestinataire(message.getEmail());
email.setObjet(message.getObjet());
//email.setTexte("eljfdksjlfhdskjfsdhfkds");
RequestContext.getCurrentInstance().update(":form1:dlg3");
//System.out.println(this.message.getNomComplet());
}
public void sendEmail()
{
/*System.out.println("Send Email");
System.out.println(email.getObjet());
System.out.println(email.getTexte());
System.out.println(email.getDestinataire());*/
//FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"En Cours","En Cours d'envoi"));
#SuppressWarnings("unused")
EmailSender sender = new EmailSender(email);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Succès","Message Envoyé"));
//System.out.println("après emailSender");
}
public Email getEmail() {
return email;
}
public void setEmail(Email email) {
this.email = email;
}
public String getReponse() {
return reponse;
}
public void setReponse(String reponse) {
this.reponse = reponse;
}
}
i have solved my problem it was
messageFacade = new MessageFacade(); must be in the constructor and not in a the function getMessages()

How to use j_security_check jsf

I want to use j_security_check authentication in order to validate the user credentials.
Basically what I am trying to achieve is when the user press submit then in case he is using wrong credentials then a message (p:growl) will show and if it’s successful then the dialog will closed.
There are many examples in the web but unfortunately I still can’t understand how to complete this puzzle :(
In my project I am using primefaces 4.0 & weblogic 10.3.2.0 (JAVA EE 5).
some code example:
<p:dialog id="dialog" widgetVar="dlg" resizable="false">
<h:form id="fLogin" prependId="false"
onsubmit="document.getElementById('fLogin').action = 'j_security_check';">
<h:panelGrid columns="2" cellpadding="5">
<h:outputLabel for="j_username" value="Username:" />
<p:inputText value="#{expBean.username}"
id="j_username" label="username"/>
<h:outputLabel for="j_password" value="Password:" />
<h:inputSecret value="#{expBean.password}"
id="j_password" label="password"/>
<p:commandButton id="submitButton"
value="Submit"
actionListener="#{expBean.run}" />
</h:panelGrid>
</h:form>
</p:dialog>
web.xml
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<security-constraint>
<web-resource-collection>
<web-resource-name>main</web-resource-name>
<description/>
<url-pattern>main.jsf</url-pattern>
<http-method>POST</http-method>
</web-resource-collection>
</security-constraint>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>my-realm</realm-name>
</login-config>
<security-role>
<description/>
<role-name>MyRole</role-name>
</security-role>
exeBean:
public void run() {
FacesContext facesContext = FacesContext.getCurrentInstance();
}
Any guidelines and useful example will be much appreciated
Thanks
You were submitting the form by PrimeFaces ajax. That's why it fails. The j_security_check handler doesn't understand incoming JSF/PrimeFaces-flavored ajax requests and can't handle them appropriately by returning the desired XML response. It has to be a regular (synchronous) submit.
Turn off the ajax thing:
<p:commandButton ... ajax="false" />
By the way, your form declaration is clumsy. Just use <form> instead of <h:form>.
<form id="fLogin" action="j_security_check">
after experimenting some strategy, i choose not to use j_security_check and implement auth this way:
#ManagedBean
#ViewScoped
public class AuthBean implements Serializable
{
private static final long serialVersionUID = 1L;
private static final Logger logger = LoggerFactory.getLogger(AuthBean.class);
#EJB
private PersistenceService service;
#ManagedProperty("#{user}")
private UserBean userBean;
private String email;
private String password;
private String originalURL;
#PostConstruct
public void init()
{
logger.debug("called");
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
originalURL = (String) externalContext.getRequestMap().get(RequestDispatcher.FORWARD_REQUEST_URI);
if(originalURL == null)
{
originalURL = externalContext.getRequestContextPath();
}
else
{
String originalQuery = (String) externalContext.getRequestMap().get(RequestDispatcher.FORWARD_QUERY_STRING);
if(originalQuery != null)
{
originalURL += "?" + originalQuery;
}
}
logger.debug("originalURL: {}", originalURL);
}
public void login() throws IOException
{
logger.debug("called");
logger.debug("originalURL: {}", originalURL);
FacesContext context = FacesContext.getCurrentInstance();
ExternalContext externalContext = context.getExternalContext();
HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
try
{
request.login(email, password);
}
catch(ServletException e)
{
JsfUtils.addErrorMessage(e, "authentication failed");
return;
}
Person person = service.queryOne(Person.class, "SELECT x FROM Person x WHERE x.email = ?1", email);
if(person == null)
{
JsfUtils.addErrorMessage("authorization failed");
return;
}
userBean.setPerson(person);
externalContext.redirect(originalURL);
}
public void logout() throws IOException
{
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
externalContext.invalidateSession();
externalContext.redirect(externalContext.getRequestContextPath());
}
// getters/setters
}
using this form inside /login.xhtml:
<h:form>
<p:panel header="#{bundle.login}">
<h:panelGrid columns="3">
<h:outputLabel for="email" value="#{bundle.email}" />
<h:outputLabel for="password" value="#{bundle.password}" />
<h:panelGroup />
<p:inputText id="email" value="#{authBean.email}" label="#{bundle.email}" size="32" />
<p:password id="password" value="#{authBean.password}" label="#{bundle.password}" feedback="false" size="32" />
<p:commandButton value="#{bundle.login}" action="#{authBean.login}" icon="ui-icon ui-icon-check" />
</h:panelGrid>
</p:panel>
</h:form>
and this login-config:
<login-config>
<auth-method>FORM</auth-method>
<realm-name>some-realm-name</realm-name>
<form-login-config>
<form-login-page>/login.jsf</form-login-page>
<form-error-page>/login.jsf</form-error-page>
</form-login-config>
</login-config>

Managed Property returns null

I've a Ajax post request form *input_graph.xhtml* which is backed by a View scoped bean InputTablePlot.java, I've an application scoped bean with eager=true, which creates a connection pool on application start. I have injected this application scoped bean as a managed property in InputTablePlot, and I retrieve connection object from it. The connection pool is available in partial submits but is NULL in submit method which is invoked by clicking a command button "Plot".
Input.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:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<f:view contentType="text/html">
<h:head>
</h:head>
<h:body>
<h:panelGroup id="container" style="background-color: white"
layout="block">
<h:panelGroup id="center" class="column" layout="block">
<h:form>
<p:messages id="validations" />
<p:panelGrid columns="2" styleClass="panelgrid">
<h:outputLabel for="ip" value="Source:"></h:outputLabel>
<p:selectManyMenu id="ip" value="#{inputTablePlot.ipAddress}"
required="true" requiredMessage="Enter Source">
<f:selectItems value="#{inputTablePlot.ipAddressList}" />
<p:ajax listener="#{inputTablePlot.populateDstn}" event="change"
update="dstn" process="#this"/>
</p:selectManyMenu>
<h:outputLabel for="dstn" value="Destination:"></h:outputLabel>
<p:selectManyMenu id="dstn" value="#{inputTablePlot.m_destination}"
required="true" requiredMessage="Enter Destination">
<f:selectItems value="#{inputTablePlot.m_destinationMenu}" />
</p:selectManyMenu>
<h:outputLabel for="start_date">Start Date/Time:</h:outputLabel>
<p:calendar id="start_date" value="#{inputTablePlot.startDtTime}"
navigator="true" pattern="MM/dd/yyyy hh:mm:ss a" required="true"
requiredMessage="Enter Start Date/Time" effect="fadeIn">
</p:calendar>
<h:outputLabel for="stop_date">Stop Date/Time:</h:outputLabel>
<p:calendar id="stop_date" value="#{inputTablePlot.stopDtTime}"
navigator="true" pattern="MM/dd/yyyy hh:mm:ss a" required="true"
requiredMessage="Enter Stop Date/Time" effect="fadeIn">
</p:calendar>
<h:outputLabel>Period:</h:outputLabel>
<p:selectOneMenu value="#{inputTablePlot.selPeriodType}"
required="true" requiredMessage="Enter Period">
<f:selectItems value="#{inputTablePlot.periodType}" />
<p:ajax listener="#{inputTablePlot.modifyperiod}" event="change"
process="#this" partialSubmit="true"/>
</p:selectOneMenu>
<p:inputText id="txt1" value="#{inputTablePlot.period}" />
<p:slider for="txt1" id="slider"/>
<h:commandButton value="Plot" action="#{inputTablePlot.submit}"
styleClass="button" id="bt2"></h:commandButton>
<h:commandButton value="Clear" action="#{inputTablePlot.clear}"
styleClass="button"></h:commandButton>
</p:panelGrid>
<p:defaultCommand target="bt2" />
</h:form>
</h:panelGroup>
</h:panelGroup>
</h:body>
</f:view>
</html>
InputTablePlot.java
#ManagedBean
#ViewScoped
public class InputTablePlot implements Serializable
{
private List<Long> m_ipAddress;
private Map<String, Long> m_ipAddrMenu;
private List<Long> m_destination;
private Map<String, Long> m_destinationMenu;
private List<Long> m_ssrc;
private Map<String, Long> m_ssrcMenu;
private Date m_startDtTime;
private Date m_stopDtTime;
private int m_period;
private List<String> m_periodType;
private String m_selectedPrdType;
#ManagedProperty("#{analyzerUIDatabase}")
private transient AnalyzerUIDatabase m_analyzerUIDatabase;
private List<List<PeriodStats>> m_results;
private StringBuilder m_query;
public InputTablePlot()
{
m_ipAddrMenu = new LinkedHashMap<String, Long>();
m_destinationMenu = new LinkedHashMap<String, Long>();
m_periodType = new ArrayList<String>();
m_results = new ArrayList<List<PeriodStats>>();
m_period = 10;
m_query = new StringBuilder();
}
#PostConstruct
public void init()
{
m_ipAddrMenu.clear();// Removing existing sources
m_destinationMenu.clear();// Removing existing destinations
m_periodType.clear();// Removing existing period types
m_periodType.add("Seconds");
m_periodType.add("Minutes");
m_periodType.add("Hours");
m_periodType.add("Days");
try
{
Connection m_connection = null;
ResultSet m_rs = null;
PreparedStatement m_pst_query = null;
m_query.setLength(0);
m_connection = m_analyzerUIDatabase.getConnection();
//process query
m_pst_query = m_connection.prepareStatement(m_query.toString());
m_rs = m_pst_query.executeQuery();
while (m_rs.next())
{
m_ipAddrMenu.put(ipLongToString(m_rs.getLong("IPADDRESS")), m_rs.getLong("IPADDRESS"));
}
m_rs.close();
m_query.setLength(0);
m_pst_query.close();
m_connection.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
> //Getters and Setters
public String submit()
{
System.out.println("In Submit >>>>>>>> ");
log(m_analyzerUIDatabase); // <--
> Returning NULL
log(m_startDtTime);
log(m_stopDtTime);
log(m_selectedPrdType);
log(m_period);
log(m_ipAddress);
log(m_destination);
if (m_startDtTime.after(m_stopDtTime))
{
FacesContext facesContext = FacesContext.getCurrentInstance();
FacesMessage facesMessage = new FacesMessage("Stop Date/Time should be after Start Date/Time");
facesContext.addMessage("tableplot:validations", facesMessage);
return "FAILURE";
}
else if (m_selectedPrdType.equalsIgnoreCase("Seconds") && m_period < 10)
{
FacesContext facesContext = FacesContext.getCurrentInstance();
FacesMessage facesMessage = new FacesMessage("Minimum Period in Seconds is 10");
facesContext.addMessage("tableplot:validations", facesMessage);
return "FAILURE";
}
else
{
Connection m_connection = null;
ResultSet m_rs = null;
PreparedStatement m_pst_query = null;
for (int i = 0; i < m_ipAddress.size(); i++)
{
// Execute some logic
Flash flash = FacesContext.getCurrentInstance().getExternalContext().getFlash();
flash.put("m_results", m_results);
flash.put("resultJSON", resultJSON);
return "SUCCESS";
}
}
public void populateDstn()
{
System.out.println("ipaddr : " + this.m_ipAddress);
Connection m_connection = null;
ResultSet m_rs = null;
PreparedStatement m_pst_query = null;
try
{
m_destinationMenu.clear();
m_connection = m_analyzerUIDatabase.getConnection();
//execute some logic
m_rs.close();
m_query.setLength(0);
ipAddress.setLength(0);
m_pst_query.close();
m_connection.close();
}
catch (SQLException e)
{
FacesContext.getCurrentInstance().addMessage("tableplot:validations", new FacesMessage("Problem fetching Destinations"));
e.printStackTrace();
}
}
private void log(Object object)
{
String methodName = Thread.currentThread().getStackTrace()[2].getMethodName();
System.out.println("MyBean " + methodName + ": " + object);
}
}
StackTrace
START PHASE RESTORE_VIEW 1
userAgent ::: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36 accept :: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
userAgent ::: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36 accept :: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
userAgent ::: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36 accept :: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
END PHASE RESTORE_VIEW 1
START PHASE APPLY_REQUEST_VALUES 2
END PHASE APPLY_REQUEST_VALUES 2
START PHASE PROCESS_VALIDATIONS 3
MyBean getIpAddress: [168821850]
MyBean getIpAddress: [168821850]
MyBean getM_destination: null
MyBean getM_destination: null
END PHASE PROCESS_VALIDATIONS 3
START PHASE UPDATE_MODEL_VALUES 4
MyBean setIpAddress: [168821850]
MyBean setM_destination: [168821876]
END PHASE UPDATE_MODEL_VALUES 4
START PHASE INVOKE_APPLICATION 5
In Submit >>>>>>>>
MyBean submit: null
MyBean submit: Wed Jul 17 00:00:00 CDT 2013
MyBean submit: Fri Jul 19 00:00:00 CDT 2013
MyBean submit: Seconds
MyBean submit: 10
MyBean submit: [168821850]
MyBean submit: [168821876]
java.lang.NullPointerException
at com.InputTablePlot.submit(InputTablePlot.java:298)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.sun.el.parser.AstValue.invoke(AstValue.java:234)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:297)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:681)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:452)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:138)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:564)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:213)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1083)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:379)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:175)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1017)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:136)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
at org.eclipse.jetty.server.Server.handle(Server.java:445)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:260)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:225)
at org.eclipse.jetty.io.AbstractConnection$ReadCallback.run(AbstractConnection.java:358)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:596)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:527)
at java.lang.Thread.run(Thread.java:722)
END PHASE INVOKE_APPLICATION 5
START PHASE RENDER_RESPONSE 6
MyBean getIpAddress: [168821850]
MyBean getIpAddress: [168821850]
MyBean getM_destination: [168821876]
MyBean getM_destination: [168821876]
END PHASE RENDER_RESPONSE 6

How to create JSF Table with links after post

I like to display a form where the end-user can enter details and the post will result in the table which contain a filtered list based on the user input. This table should have link for each row to select that specific row and return a detailed view.
accounts-list.xhtml:
<?xml version="1.0" encoding="UTF-8"?>
<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:h="http://java.sun.com/jsf/html"
xmlns:utils="http://java.sun.com/jsf/composite/snippets" template="/WEB-INF/templates/default.xhtml">
<ui:define name="title"></ui:define>
<ui:define name="content">
<h:form id="search">
<fieldset>
<legend>Search for account</legend>
<div class="account_list_section">
<span class="account_section_title"><h:outputLabel for="id" value="Account ID" /></span>
<span class="account_list_item">
<h:inputText id="id" value="#{accountsCrudBean.searchId}" styleClass="field_inputtext_account" />
</span>
</div>
<div class="account_list_section">
<span class="account_section_title"><h:outputLabel for="name" value="Account Name" /></span>
<span class="account_list_item">
<h:inputText id="name" value="#{accountsCrudBean.searchName}" styleClass="field_inputtext_account" />
</span>
</div>
<h:commandButton id="search" value="Display" action="#{accountsCrudBean.actionSearch}" />
</fieldset>
</h:form>
<h:form id="view" rendered="#{accountsCrudBean.dataItemId.value != null}">
<h:dataTable var="dataItem" binding="#{accountsCrudBean.dataTable}" value="#{accountsCrudBean.list}" id="accountListTable"
columnClasses="accountsCrudBeanTable_row_date, transactionsListTable_row_amount, transactionsListTable_row_balance, transactionsListTable_row_description" styleClass="transactionsListTable">
<h:column headerClass="transactionsListTable_header_amount">
<f:facet name="header">Id</f:facet>
<h:commandLink value="#{dataItem.id}" action="#{accountsCrudBean.editDataItem}" />
</h:column>
<h:column headerClass="transactionsListTable_header_balance">
<f:facet name="header">Name</f:facet>#{dataItem.name}</h:column>
<h:column headerClass="transactionsListTable_header_description">
<f:facet name="header">Total Balance</f:facet>#{dataItem.totalBalance}</h:column>
</h:dataTable>
<h:inputHidden binding="#{accountsCrudBean.dataItemId}" />
</h:form>
</ui:define>
</ui:composition>
accounts-edit.xhtml:
<?xml version="1.0" encoding="UTF-8"?>
<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:h="http://java.sun.com/jsf/html"
xmlns:utils="http://java.sun.com/jsf/composite/snippets"
template="/WEB-INF/templates/default.xhtml">
<ui:define name="title"></ui:define>
<ui:define name="content">
<h:form id="edit" rendered="#{accountsCrudBean.dataItemId.value != null}">
<fieldset>
<legend>View account 1</legend>
<div class="account_list_section">
<span class="account_section_title"><h:outputLabel for="id" value="Account ID" /></span>
<span class="account_list_item">
#{accountsCrudBean.dataItemId.value}
</span>
</div>
<div class="account_list_section">
<span class="account_section_title"><h:outputLabel for="name" value="Account Name" /></span>
<span class="account_list_item">
<h:inputText readonly="true" id="name" value="#{accountsCrudBean.dataItem.name}" styleClass="field_inputtext_account" />
</span>
</div>
<div class="account_list_section">
<span class="account_section_title"><h:outputLabel for="accountOwners" value="Owners" /></span>
<span class="account_list_item">
<h:selectOneListbox readonly="true" id="accountOwners" value="#{accountsCrudBean.selectedOwner}">
<f:selectItems value="#{accountsCrudBean.accountOwners}" />
</h:selectOneListbox>
</span>
</div>
<h:inputHidden binding="#{accountsCrudBean.dataItemId}" />
<h:commandButton id="edit" value="Save" action="#{accountsCrudBean.actionSearch}" />
</fieldset>
</h:form>
<h:outputText value="No item selected." rendered="#{accountsCrudBean.dataItemId.value == null}" />
</ui:define>
</ui:composition>
AccountsCrudBean.java:
#ManagedBean
#SessionScoped
public class AccountsCrudBean extends JsfManagedBeanBase {
private static final long serialVersionUID = 1L;
#EJB
AccountsManagerLocal accountsManager;
private Long searchId;
private String searchName;
private String selectedOwner;
private Account dataItem;
private HtmlDataTable dataTable;
private HtmlInputHidden dataItemId = new HtmlInputHidden();
private List<Account> accountList = null;
public AccountsCrudBean() {
}
public Long getSearchId() {
return searchId;
}
public void setSearchId(Long searchId) {
this.searchId = searchId;
}
public String getSearchName() {
return searchName;
}
public void setSearchName(String searchName) {
this.searchName = searchName;
}
public HtmlInputHidden getDataItemId() {
return dataItemId;
}
public Account getDataItem() {
return dataItem;
}
public void setDataItem(Account dataItem) {
this.dataItem = dataItem;
}
public HtmlDataTable getDataTable() {
return dataTable;
}
public void setDataTable(HtmlDataTable dataTable) {
this.dataTable = dataTable;
}
public void setDataItemId(HtmlInputHidden dataItemId) {
this.dataItemId = dataItemId;
}
public String getSelectedOwner() {
return selectedOwner;
}
public void setSelectedOwner(String selectedOwner) {
this.selectedOwner = selectedOwner;
}
public List<Account> getList() {
if (accountList == null) {
actionLoad();
}
return accountList;
}
private void actionLoad() {
if (searchId != null) {
Account account = accountsManager.getAccount(searchId);
accountList = Arrays.asList(account);
} else if (searchName != null) {
accountList = accountsManager.findAccountByName(searchName);
} else if (dataItemId != null && dataItemId.getValue() != null) {
Account account = accountsManager.getAccount(Long
.valueOf(dataItemId.getValue().toString()));
accountList = Arrays.asList(account);
} else
accountList = new ArrayList<Account>();
};
public void actionSearch() {
dataItem = (Account) dataTable.getRowData();
dataItemId.setValue(dataItem.getId());
actionLoad();
}
public Map<String, User> getAccountOwners() {
List<User> owners = accountsManager.getUsers(dataItem);
LinkedHashMap<String, User> map = new LinkedHashMap<String, User>();
for (User user : owners) {
map.put(user.getFirstName() + " " + user.getLastName(), user);
}
return map;
}
public String editDataItem() {
dataItem = (Account) dataTable.getRowData();
dataItemId.setValue(dataItem.getId());
return "accounts-edit";
}
}
This works on JBoss 7.1 but on 6 it's failed with:
javax.faces.el.EvaluationException: javax.el.ELException: /s/accounts-list.xhtml at line 22 and column 94 action="#{accountsCrudBean.actionSearch}": java.lang.IllegalArgumentException: row is unavailable
at javax.faces.component._MethodExpressionToMethodBinding.invoke(_MethodExpressionToMethodBinding.java:96)
at org.apache.myfaces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:100)
at javax.faces.component.UICommand.broadcast(UICommand.java:120)
at javax.faces.component.UIViewRoot._broadcastAll(UIViewRoot.java:889)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:238)
at javax.faces.component.UIViewRoot._process(UIViewRoot.java:1201)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:627)
at org.apache.myfaces.lifecycle.InvokeApplicationExecutor.execute(InvokeApplicationExecutor.java:34)
at org.apache.myfaces.lifecycle.LifecycleImpl.executePhase(LifecycleImpl.java:171)
at org.apache.myfaces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:189)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:324)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:242)
at org.jboss.weld.servlet.ConversationPropagationFilter.doFilter(ConversationPropagationFilter.java:67)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:274)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:242)
at com.demo.server.ejb.security.AuthenticationFilter.doFilter(AuthenticationFilter.java:35)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:274)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:242)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:275)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161)
at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:181)
at org.jboss.modcluster.catalina.CatalinaContext$RequestListenerValve.event(CatalinaContext.java:285)
at org.jboss.modcluster.catalina.CatalinaContext$RequestListenerValve.invoke(CatalinaContext.java:261)
at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:88)
at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.invoke(SecurityContextEstablishmentValve.java:100)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:159)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.jboss.web.tomcat.service.request.ActiveRequestResponseCacheValve.invoke(ActiveRequestResponseCacheValve.java:53)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:362)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:654)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:951)
at java.lang.Thread.run(Thread.java:722)
Caused by: javax.el.ELException: /s/accounts-list.xhtml at line 22 and column 94 action="#{accountsCrudBean.actionSearch}": java.lang.IllegalArgumentException: row is unavailable
at org.apache.myfaces.view.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:95)
at javax.faces.component._MethodExpressionToMethodBinding.invoke(_MethodExpressionToMethodBinding.java:88)
... 35 more
Caused by: java.lang.IllegalArgumentException: row is unavailable
at javax.faces.model.ListDataModel.getRowData(ListDataModel.java:69)
at javax.faces.component.UIData.getRowData(UIData.java:462)
at com.demo.server.web.AccountsCrudBean.actionSearch(AccountsCrudBean.java:130)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.apache.el.parser.AstValue.invoke(AstValue.java:196)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:276)
at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:43)
at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:56)
at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:43)
at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:56)
at org.apache.myfaces.view.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:83)
... 36 more
This is based on http://balusc.blogspot.com/2006/06/using-datatables.html#AddBackingBeanActionToEveryRow
On the post the author use #RequestScoped bean but if I try to change the bean to be #RequestScoped the filter does not work, and i don't get the table with the links.
Thanks.
Your bean is in the session scope. You don't need the <h:inputHidden binding="..."> at all. Remove it and all related code. Your backing bean action methods should look like this:
public void actionSearch() {
actionLoad();
}
public String editDataItem() {
dataItem = (Account) dataTable.getRowData();
return "accounts-edit";
}
Also replace #{accountsCrudBean.dataItemId} in your view by #{accountsCrudBean.dataItem.id}.
Unrelated to the concrete problem, please note that the article is nearly 6 years old and based on JSF 1.x. These days, with JSF 2.x and EL 2.2, there are other and easier ways to get the selected row. My favourite is
<h:commandLink value="#{dataItem.id}" action="#{accountsCrudBean.editDataItem(dataItem)}" />
with
public String editDataItem(Account dataItem) {
this.dataItem = dataItem;
return "accounts-edit";
}

Resources