Managed Property returns null - jsf-2

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

Related

p:dataTable RowEdit keeping old values

I'm trying to update a value of a line edited on the datatable (editable = true, row edition). But I always keep getting the old value through the listener. Can you pls tell me where's my mistake? tks..
Here is the code:
<?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"
xmlns:p="http://primefaces.org/ui">
<ui:composition template="_template.xhtml">
<ui:define name="conteudo">
<h:form id="certificacao" >
<p:messages globalOnly="false" showSummary="true" showDetail="true" />
<p:growl id="messages" autoUpdate = "true"/>
<p:fieldset legend="Dados da Certificação">
<h:panelGrid columns="3" >
<p:outputLabel value="Nome da Certificação:" for="nomeCertificacao" style="font-weight:bold"/>
<p:inputText id="nomeCertificacao" value="#{certificacaoBean.certificacao.nomeCertificacao}"
required="true" requiredMessage="Nome da certificação não preenchido" >
</p:inputText>
<br/>
<h:outputLabel value="Descrição da Certificação:" for="descCertificacao" style="font-weight:bold"/>
<p:inputText id="descCertificacao" value="#{certificacaoBean.certificacao.descCertificacao}">
</p:inputText>
<br/>
<p:commandButton value="Gravar" action="#{certificacaoBean.gravar}" icon="fa fa-fw fa-save"
process="#this certificacao" update="#form certificacao" />
<br/>
</h:panelGrid>
</p:fieldset>
<p:dataTable
value="#{certificacaoBean.certificacoes}"
var="certificacao"
id="tabelaCertificacoes"
emptyMessage="Nenhuma certificação cadastrada"
editable="true"
style="margin-bottom:0px"
filteredValue="#{certificacaoBean.certificacaoSelecionada}"
widgetVar="tabelaCertificacoes">
<p:ajax event="rowEdit" listener="#{certificacaoBean.onRowEdit}" update=":certificacao:messages"/>
<p:ajax event="rowEditCancel" listener="#{certificacaoBean.onRowCancel}" update=":certificacao:messages" />
<p:column
headerText="Certificação"
filterBy="#{certificacao.nomeCertificacao}"
filterMatchMode="contains">
<p:cellEditor>
<f:facet name="output">
<div align="center">
<h:outputText value="#{certificacao.nomeCertificacao}" />
</div>
</f:facet>
<f:facet name="input">
<p:inputText value="#{certificacao.nomeCertificacao}" style="width:100%" label="Certificação"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Descrição" filterBy="#{certificacao.descCertificacao}" filterMatchMode="contains">
<p:cellEditor>
<f:facet name="output"><h:outputText value="#{certificacao.descCertificacao}" /></f:facet>
<f:facet name="input"><p:inputText value="#{certificacao.descCertificacao}" style="width:100%" label="Descrição"/></f:facet>
</p:cellEditor>
</p:column>
<p:column style="width:3px">
<p:rowEditor />
</p:column>
<p:column style="width:3px">
<f:facet name="header">
<h:outputText value="" style="width:3px"/>
</f:facet>
<p:commandButton
action="#{certificacaoBean.removeCertificacao(certificacao)}"
icon="ui-icon-close"
title="Remover Certificação"
update="tabelaCertificacoes"
process="#this" >
<f:setPropertyActionListener
target="#{certificacaoBean.certificacaoSelecionada}"
value="#{certificacao}" />
</p:commandButton>
</p:column>
</p:dataTable>
</h:form>
</ui:define>
The bean part:
import java.io.Serializable;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.primefaces.event.CellEditEvent;
import org.primefaces.event.RowEditEvent;
import br.com.dao.DAO;
import br.com.model.Certificacao;
#ManagedBean(name="certificacaoBean")
#ViewScoped
public class CertificacaoBean implements Serializable {
private static final long serialVersionUID = 1L;
private Certificacao certificacao = new Certificacao();
public void setCertificacao(Certificacao certificacao) {
this.certificacao = certificacao;
}
private Certificacao certificacaoSelecionada;
public Certificacao getCertificacao() {
return certificacao;
}
public Certificacao getCertificacaoSelecionada() {
return certificacaoSelecionada;
}
public void setCertificacaoSelecionada(Certificacao certificacaoSelecionada) {
this.certificacaoSelecionada = certificacaoSelecionada;
}
public void removeCertificacao(Certificacao certificacao) {
new DAO<Certificacao>(Certificacao.class).remove(certificacaoSelecionada);
FacesMessage msg = new FacesMessage("Certificação excluída","");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public List<Certificacao> getCertificacoes() {
return new DAO<Certificacao>(Certificacao.class).listaTodos();
}
public void gravar() {
System.out.println("Gravando Certificação " + this.certificacao.getNomeCertificacao());
if (certificacao.getNomeCertificacao().isEmpty()) {
FacesContext.getCurrentInstance().addMessage ("nomeCertificacao",
new FacesMessage(FacesMessage.SEVERITY_ERROR,
"O nome da certificação deve ser preenchido.", "O nome da certificação deve ser preenchido."));
return;
}
new DAO<Certificacao>(Certificacao.class).adiciona(this.certificacao);
this.certificacao = new Certificacao();
}
// Inicio Editor na Tabela
public void onRowEdit(RowEditEvent event) {
System.out.println("Passando no DAO retorno event Cod: " + ((((Certificacao) event.getObject()).getCodigoCertificacao())));
System.out.println("Passando no DAO retorno event Name: " + ((((Certificacao) event.getObject()).getNomeCertificacao())));
System.out.println("Passando no DAO retorno object: " + ((((Certificacao) event.getObject()))));
System.out.println("DAO evento " + event);
//new DAO<Certificacao>(Certificacao.class).adiciona(this.certificacao);
//Problema AQUI
new DAO<Certificacao>(Certificacao.class).atualiza((((Certificacao) event.getObject())));
this.certificacao = new Certificacao();
FacesMessage msg = new FacesMessage("Certificação editada", String.valueOf((((Certificacao) event.getObject()).getCodigoCertificacao())));
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onRowCancel(RowEditEvent event) {
FacesMessage msg = new FacesMessage("Edição cancelada", String.valueOf((((Certificacao) event.getObject()).getCodigoCertificacao())));
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onCellEdit(CellEditEvent event) {
Object oldValue = event.getOldValue();
Object newValue = event.getNewValue();
if(newValue != null && !newValue.equals(oldValue)) {
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Cell Changed", "Old: " + oldValue + ", New:" + newValue);
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
}
And the dao:
package br.com.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaQuery;
public class DAO<T> {
private final Class<T> classe;
public DAO(Class<T> classe) {
this.classe = classe;
}
public void adiciona(T t) {
// consegue a entity manager
EntityManager em = new JPAUtil().getEntityManager();
// abre transacao
em.getTransaction().begin();
// persiste o objeto
em.persist(t);
// commita a transacao
em.getTransaction().commit();
// fecha a entity manager
em.close();
}
public void remove(T t) {
EntityManager em = new JPAUtil().getEntityManager();
em.getTransaction().begin();
em.remove(em.merge(t));
em.getTransaction().commit();
em.close();
}
public void atualiza(T t) {
EntityManager em = new JPAUtil().getEntityManager();
em.getTransaction().begin();
em.merge(t);
em.getTransaction().commit();
em.close();
}
public List<T> listaTodos() {
EntityManager em = new JPAUtil().getEntityManager();
CriteriaQuery<T> query = em.getCriteriaBuilder().createQuery(classe);
query.select(query.from(classe));
List<T> lista = em.createQuery(query).getResultList();
em.close();
return lista;
}
public T buscaPorId(Integer id) {
EntityManager em = new JPAUtil().getEntityManager();
T instancia = em.find(classe, id);
em.close();
return instancia;
}
public int contaTodos() {
EntityManager em = new JPAUtil().getEntityManager();
long result = (Long) em.createQuery("select count(n) from certificacao n")
.getSingleResult();
em.close();
return (int) result;
}
public List<T> listaTodosPaginada(int firstResult, int maxResults) {
EntityManager em = new JPAUtil().getEntityManager();
CriteriaQuery<T> query = em.getCriteriaBuilder().createQuery(classe);
query.select(query.from(classe));
List<T> lista = em.createQuery(query).setFirstResult(firstResult)
.setMaxResults(maxResults).getResultList();
em.close();
return lista;
}
}
In your code, You only update the message'id not the datatable's id. Try to update the form in the "update" attribute of ajax when edit the row.

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>

Load value from database to <h:inputText> with <h:selectOneMenu> valueChangeEvent

I want to develop a JSF Page which lets user edit a Employee from database. I loaded list of all employees in h:selectOneMenu. and second thing i want that with valueChangeEvent employee detail should be loaded in corresponding h:inputText. but nothing happens with every valueChangeEvent. So, where is the problem in codes.
<?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://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<div id="hdr">
<h1>Vinweb Services</h1>
<hr/>
</div>
;
<div id="mnu" style="height: 50px; width: auto; background: skyblue;">
<h:form>
<h:commandLink value="Home" action="index"/>
<h:outputText value=" "/>
<h:commandLink value="Create" action="create"/>
<h:outputText value=" "/>
<h:commandLink value="View" action="view"/>
<h:outputText value=" "/>
<h:commandLink value="Edit" action="edit"/>
</h:form>
</div>
<div id="cnt">
<h:form>
<h:panelGrid columns="2">
<h:outputLabel value="Select an Employee"/>
<h:selectOneMenu value="#{esb.empName}" onchange="submit()" valueChangeListener="#{esb.loadEmployeeDetail}">
<f:selectItems value="#{esb.employeeList}"/>
</h:selectOneMenu>
<h:outputLabel value="Employee Code"/>
<h:inputText value="#{esb.empCode}" required="true"/>
<h:outputLabel value="Employee Name"/>
<h:inputText value="#{esb.empName}" required="true"/>
<h:outputLabel value="Joining Date"/>
<h:inputText value="#{esb.joinDate}" required="true">
<f:convertDateTime pattern="MM/yy"/>
</h:inputText>
<h:outputLabel value="Salary"/>
<h:inputText value="#{esb.salary}" required="true"/>
<h:commandButton value="Update" action="#{esb.updateEmployeeDetail}"/>
</h:panelGrid>
</h:form>
</div>
</h:body>
</html>
Backing Bean:
package ems.bean;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import javax.annotation.Resource;
import javax.faces.event.ValueChangeEvent;
import javax.sql.DataSource;
#Named(value = "esb")
#SessionScoped
public class EmployeeServiceBean implements Serializable {
#Resource(name = "JPA4A")
private DataSource ds;
// Member Declaration
private String empCode;
private String empName;
private Date joinDate;
private long salary;
private ArrayList empList;
// Service Code Segment
// This method will publish all emloyees in table to selectOneMenu
public ArrayList getEmployeeList() throws SQLException{
empList = new ArrayList();
Connection con = ds.getConnection();
try{
Statement stmt = con.createStatement();
ResultSet rslt = stmt.executeQuery("SELECT empName FROM Employee");
while(rslt.next()){
empList.add(rslt.getString("empName"));
}
}
catch(SQLException se) {
throw new SQLException();
}
finally{
con.close();
}
return empList;
}
// This method should load selected empoyee's details in inputText fields
public void loadEmployeeDetail(ValueChangeEvent evt) throws SQLException{
String emp = evt.getNewValue().toString();
Connection con = ds.getConnection();
try{
Statement stmt = con.createStatement();
String qry = "SELECT * FROM Employee WHERE empName = '"+emp+"'";
ResultSet rslt = stmt.executeQuery(qry);
rslt.next();
this.empCode = rslt.getString("empCode");
this.empName = rslt.getString("empName");
this.joinDate = rslt.getDate("joinDate");
this.salary = rslt.getLong("salary");
}
catch(SQLException se) {
se.printStackTrace();
}
finally{
con.close();
}
}
public void updateEmployeeDetail() throws SQLException{
Connection con = ds.getConnection();
try{
Statement stmt = con.createStatement();
boolean rs = stmt.execute("UPDATE Employee SET empCode='"+empCode+"', empName='"+empName+"', joinDate='"+joinDate+"', salary="+salary);
}
catch(SQLException se) {
throw new SQLException();
}
finally{
con.close();
}
}
// Property Getter & Setter code segment
public String getEmpCode() {
return empCode;
}
public void setEmpCode(String empCode) {
this.empCode = empCode;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public Date getJoinDate() {
return joinDate;
}
public void setJoinDate(Date joinDate) {
this.joinDate = joinDate;
}
public long getSalary() {
return salary;
}
public void setSalary(long salary) {
this.salary = salary;
}
}
The valueChangeListener is the wrong tool for the job.
You're here doing a onchange="submit()" which submits the entire form, including those required fields which in turn caused validation errors which in turn failed to reach your attention because you don't have any <h:message(s)> for them. If you have placed a <h:messages/> inside the form, or have paid more love and attention to server logs, you should have been notified of those required="true" validation errors.
You need <f:ajax listener>.
Replace
<h:selectOneMenu value="#{esb.empName}" onchange="submit()" valueChangeListener="#{esb.loadEmployeeDetail}">
<f:selectItems value="#{esb.employeeList}"/>
</h:selectOneMenu>
by
<h:selectOneMenu value="#{esb.empName}">
<f:selectItems value="#{esb.employeeList}"/>
<f:ajax listener="#{esb.loadEmployeeDetail}" render="#form" />
</h:selectOneMenu>
and replace
public void loadEmployeeDetail(ValueChangeEvent evt) throws SQLException{
String emp = evt.getNewValue().toString();
// ...
}
by
public void loadEmployeeDetail() throws SQLException{
String emp = empName; // You can also just use `empName` directly.
// ...
}
See also:
When to use valueChangeListener or f:ajax listener?

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

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.

Request parameter is null during postback

I have a view that display a list of users, from this view I can go to another view of "details" of any selected user. In the details view I need to select some values from 2 select list and then in the backed bean take these values, and add them to an user to finally store (update) the user in the database. These are my methods in the "user Bean".
With this method I get the user id from the "list of users view" and retrieve the user from the database to display its info on the details view.
public void getParam(){
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
//Obtener parametros del request
Map<String, String> parameterMap = (Map<String, String>) externalContext.getRequestParameterMap();
Long param = Long.valueOf(parameterMap.get("id_usuario"));
System.out.println(param);
this.setU(controlador.getUser(param));
}
With this method I set the values from the select list to an object and then I add this object to the user, finally I save it on the database.
public void setPrivilegio(){
System.out.println("hola");
Privilegio pri=new Privilegio();
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
//Obtener parametros del request
Map parameterMap = externalContext.getRequestParameterMap();
Agrupacion agrupacion= (Agrupacion)parameterMap.get("agrup");
System.out.println(agrupacion.getNombre());
Rol rol = (Rol)parameterMap.get("rols");
System.out.println(rol.getNombre());
System.out.println(""+rol.getNombre()+" "+agrupacion.getNombre());
pri.setRol(rol);
pri.setAgrupacion(agrupacion);
pri.setActive(true);
this.getU().addPrivilegio(pri);
controlador.saveUsuario(this.getU());
}
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">
<ui:composition 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">
<div class="container">
<h:panelGroup id="Usuarios">
<h:form id="FormUsuarios">
<h2>Detalles Usuario</h2>
<h:dataTable id="users" value="#{usuario.u}" styleClass="table table-striped table-bordered" headerClass="sorting_asc"
rowClasses="odd,even">
<h:column>
<f:facet name="header">#</f:facet>
#{usuario.u.id}
</h:column>
<h:column>
<f:facet name="header">Identificador</f:facet>
<h:inputText id="identificador" value="#{usuario.u.identificador}" />
</h:column>
<h:column>
<f:facet name="header">Nombre</f:facet>
<h:inputText id="nombres" value=" #{usuario.u.nombres}"/> <h:inputText id="apellidoP" value=" #{usuario.u.apellidoPaterno}"/> <h:inputText id="apellidoM" value=" #{usuario.u.apellidoMaterno}"/>
</h:column>
<h:column>
<f:facet name="header">Active</f:facet>
<h:selectBooleanCheckbox id="check" value="#{usuario.u.active}"></h:selectBooleanCheckbox>
</h:column>
</h:dataTable>
<h3>Asignar Privilegios</h3>
<h:selectOneMenu id="agrup" value="#{usuario.selected}" converter="omnifaces.SelectItemsConverter">
<f:selectItems value="#{agrupacion.agrupacion}" var="entity" itemLabel="#{entity.nombre}" itemValue="#{entity.id}"/>
</h:selectOneMenu>
<h:selectOneMenu id="rols" value="#{rol.selected}" converter="omnifaces.SelectItemsConverter">
<f:selectItems value="#{rol.roles}" var="rol" itemLabel="#{rol.nombre}" itemValue="#{rol.id}"/>
</h:selectOneMenu>
<h:commandButton value="Asignar" styleClass="btn-primary" actionListener="#{usuario.setPrivilegio}">
</h:commandButton>
<h3>Privilegios Asignados:</h3>
<h:dataTable id="privilegios" value="#{usuario.u.privilegios}" var="p" styleClass="table table-striped table-bordered" headerClass="sorting_asc"
rowClasses="odd,even">
<h:column>
<f:facet name="header">#</f:facet>
#{p.id}
</h:column>
<h:column>
<f:facet name="header">Roles</f:facet>
#{p.rol.nombre}
</h:column>
<h:column>
<f:facet name="header">Grupos</f:facet>
#{p.agrupacion.nombre}
</h:column>
<h:column>
<f:facet name="header">Active</f:facet>
<h:selectBooleanCheckbox id="checkbox" value="#{p.active}"></h:selectBooleanCheckbox>
</h:column>
</h:dataTable>
</h:form>
<script type="text/javascript" src="js/paging-bootstrap.js"></script>
<script type="text/javascript" src="js/contenidoc.datatable.init.js"></script>
</h:panelGroup>
</div>
</ui:composition>
When I click on my commandbutton called "Asignar" that calls the method setPrivilegio(), I get this error:
java.lang.NumberFormatException: null
at java.lang.Long.parseLong(Long.java:404)
at java.lang.Long.valueOf(Long.java:540)
at cl.uchile.sti.bean.UsuarioBean.getParam(UsuarioBean.java:114)
The tables in the view shows all the info, but when I want to call the method that add the selected items to the user and save it on the database (setPrivilegio) I get this error.
How is this caused and how can I solve it?
This is my full "user bean":
#ManagedBean(name = "usuario")
#ViewScoped
public class UsuarioBean {
private usuarioController controlador;
private Usuario u=new Usuario();
private Privilegio Selected=new Privilegio();
private Boolean active;
private long id_user;
#PostConstruct
public void init() {
controlador=new usuarioController();
}
public long getId_user() {
return id_user;
}
public void setId_user(long id_user) {
this.id_user = id_user;
}
public Privilegio getSelected() {
return Selected;
}
public void setSelected(Privilegio selected) {
Selected = selected;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
public Usuario getU() {
getParam();
return u;
}
public void setU(Usuario u) {
this.u = u;
}
private List<Usuario> usuario;
public List<Usuario> getUsuario() {
usuario=UsuarioDAO.getAll();
return usuario;
}
public Usuario getById(long id_usuario){
return u;
}
public void setUsuario(List<Usuario> usuario) {
this.usuario = usuario;
}
public void saveUsuario(Usuario u){
controlador.saveUsuario(u);
}
public void getParam(){
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
//Obtener parametros del request
Map<String, String> parameterMap = (Map<String, String>) externalContext.getRequestParameterMap();
Long param = Long.valueOf(parameterMap.get("id_usuario"));
System.out.println(param);
this.setU(controlador.getUser(param));
}
public void setPrivilegio(){
System.out.println("hola");
Privilegio pri=new Privilegio();
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
//Obtener parametros del request
Map parameterMap = externalContext.getRequestParameterMap();
Agrupacion agrupacion= (Agrupacion)parameterMap.get("agrup");
System.out.println(agrupacion.getNombre());
Rol rol = (Rol)parameterMap.get("rols");
System.out.println(rol.getNombre());
System.out.println(""+rol.getNombre()+" "+agrupacion.getNombre());
pri.setRol(rol);
pri.setAgrupacion(agrupacion);
pri.setActive(true);
this.getU().addPrivilegio(pri);
controlador.saveUsuario(this.getU());
}
}
this is the first view (list of users, from which i go to user details)
<?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">
<ui:composition 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">
<div class="container">
<h:panelGroup id="Usuarios">
<h:form id="FormUsuarios">
<h2>Listado de Usuarios</h2>
<h:graphicImage url="http://a.dryicons.com/images/icon_sets/simplistica/png/128x128/add.png" width="30" height="30"/>
<h:dataTable id="users" value="#{usuario.usuario}" var="o" styleClass="table table-striped table-bordered" headerClass="sorting_asc"
rowClasses="odd,even">
<h:column>
<f:facet name="header">#</f:facet>
#{o.id}
</h:column>
<h:column>
<f:facet name="header">Identificador</f:facet>
#{o.identificador}
</h:column>
<h:column>
<f:facet name="header">Nombre</f:facet>
#{o.nombres} #{o.apellidoMaterno} #{o.apellidoPaterno}
</h:column>
<h:column>
<f:facet name="header">Active</f:facet>
<h:selectBooleanCheckbox id="check" value="#{o.active}"></h:selectBooleanCheckbox>
</h:column>
<h:column>
<f:facet name="header">Detalles</f:facet>
<h:outputLink value="contenido/detalleUsuario.xhtml">
Detalle
<f:param name="id_usuario" value="#{o.id}" />
</h:outputLink>
</h:column>
</h:dataTable>
</h:form>
<script type="text/javascript" src="js/paging-bootstrap.js"></script>
<script type="text/javascript" src="js/contenidoc.datatable.init.js"></script>
</h:panelGroup>
</div>
</ui:composition>
Bad getter!
public Usuario getU() {
getParam();
return u;
}
The getter above is a very bad idea. You've said it yourself that the variable makes it into the usuario backing bean(this I doubt). It is just plain wrong to perform business logic inside a getter because of inconsistencies (like you're experiencing) and the fact that the getter is called multiple times during a request. There are more elegant and cleaner ways to pass and initialise parameters between JSF pages.
private Usuario u=new Usuario(); is also a bad idea. Why is this necessary when you have
this.setU(controlador.getUser(param));
All that should happen inside your #PostConstructor
#PostConstruct
public void init() {
controlador=new usuarioController();
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
//Obtener parametros del request
Map<String, String> parameterMap = (Map<String, String>) externalContext.getRequestParameterMap();
Long param = Long.valueOf(parameterMap.get("id_usuario"));
System.out.println(param);
this.setU(controlador.getUser(param));
}
The getter should just be plain
public Usuario getU() {
return u;
}
The cause of this error is that parameterMap.get("id_usuario") is null. You should investigate how you pass this parameter from the UI to the backing bean.

Resources