Problem: searching for some more suitable design .
Goal: I want to have table of some user information and with button "change password" in column for each user, after click : "change password" button disappeared (rendered ="false") and a inputSecreat field appeared - user entering the password and submitting it (by clicking some additional button or by hotkey ). after submit - "change password" button papered as before.
my bean
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.HashMap;
/**
* <p>Type: UserSession
* <p>User: kislo_metal
* <p>Date: Jun 21, 2010
* <p>Time: 4:41:57 PM
*/
#Named
#SessionScoped
public class UserSession implements Serializable {
private String name;
private String role;
#Inject
private org.slf4j.Logger log;
#EJB
private PersistenceService pservice;
#Inject
private RulesBean rules;
private HashMap<Long, Boolean> boolHashmap;
public UserSession() {
}
#PostConstruct
public void postConstruct() {
log.info("session init ");
}
public String getName() {
if (name == null) getUserData();
return name == null ? "" : name;
}
public String getRole() {
return role == null ? "" : role;
}
public void setRole(String newValue) {
role = newValue;
}
public boolean isInRole() {
ExternalContext context
= FacesContext.getCurrentInstance().getExternalContext();
Object requestObject = context.getRequest();
if (!(requestObject instanceof HttpServletRequest)) {
log.info("request object has type " + requestObject.getClass());
return false;
}
HttpServletRequest request = (HttpServletRequest) requestObject;
return request.isUserInRole(role);
}
private void getUserData() {
ExternalContext context
= FacesContext.getCurrentInstance().getExternalContext();
Object requestObject = context.getRequest();
if (!(requestObject instanceof HttpServletRequest)) {
log.info("request object has type " + requestObject.getClass());
return;
}
HttpServletRequest request = (HttpServletRequest) requestObject;
name = request.getRemoteUser();
}
public HashMap getBoolHashmap() {
if (boolHashmap == null)
initBolHashMap();
return boolHashmap;
}
public void setBoolHashmap(HashMap<Long, Boolean> boolHashmap) {
this.boolHashmap = boolHashmap;
}
public void initBolHashMap() {
this.boolHashmap = new HashMap<Long, Boolean>();
System.out.println("");
log.info("init map..");
log.info("loding list");
log.warn("user name = " + rules.getUserPrincipalName());
for (OasysUserEntity user : pservice.getUsersList(pservice.getUserByLogin(rules.getUserPrincipalName()).getPartnerid())) {
boolHashmap.put(user.getId(), false);
log.info("map =" + boolHashmap);
}
log.info("loaded list");
}
public boolean getPWRender(long id) {
if (boolHashmap == null)
initBolHashMap();
//TODO if it null - exception will be thrown
try {
log.info("getting id =" + id);
log.info("map is =" + boolHashmap);
log.info("getting result = =" + boolHashmap.get(id));
log.info("getting result = =" + boolHashmap.get(Long.valueOf(id)));
return boolHashmap.get(Long.valueOf(id));
} catch (NullPointerException e) {
e.printStackTrace();
return false;
}
}
public void setPWrenerTrue(long id) {
if (boolHashmap == null)
initBolHashMap();
log.info("setPWrenerTrue id =" + id);
boolHashmap.put(id, true);
log.info("setPWrenerTrue map is =" + boolHashmap);
}
}
and 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:cc="http://java.sun.com/jsf/composite"
xmlns:p="http://primefaces.prime.com.tr/ui"
>
<body>
<cc:interface>
</cc:interface>
<cc:implementation>
#{i18n.user_managment_title}
<h:form>
<!--<f:ajax render="#form" execute="#form">-->
<h:dataTable id="userTable" var="puser" value="#{userTable.uList}" border="1">
<h:column>
<f:facet name="header">
<h:outputText value="Login"/>
</f:facet>
#{puser.login}
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="password"/>
</f:facet>
<h:panelGroup>
<!--#{puser.password} -->
<h:commandButton id="chps" value="#{i18n.chpsqd_button}" rendered="#{!userSession.getPWRender(puser.id)}"
action="#{userSession.setPWrenerTrue(puser.id)}">
<f:ajax render="pswd chps"/>
</h:commandButton>
<h:inputSecret id="pswd" rendered="#{userSession.getPWRender(puser.id)}" value="some"/>
<!--<h:inputSecret id="chpaswd" value="#{managePUser.password}">-->
<!--<f:ajax event="click" render="chpaswd"/>-->
<!--</h:inputSecret>-->
<!--<h:commandButton value="#{i18n.submit_button}">-->
<!--</h:commandButton>-->
</h:panelGroup>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="pId"/>
</f:facet>
#{puser.partnerid}
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="groupName"/>
</f:facet>
#{puser.groupName}
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="isActive"/>
</f:facet>
#{puser.userStatusid==2}
</h:column>
<h:column>
<h:commandButton value="#{i18n.delete_button}" action="#{managePUser.removeEntity(puser)}"
disabled="#{puser.groupName.equals('admin')}">
<f:ajax render="#form"/>
</h:commandButton>
</h:column>
<!--<h:column>-->
<!---->
<!--<h:commandButton value="#{i18n.edit_button}" action="#{managePUser.removeEntity(puser)}"/>-->
<!--</h:column>-->
<f:facet name="footer">
<!--<f:ajax render="footeradd userTable">-->
<h:panelGroup id="footeradd">
<h:panelGroup layout="block" rendered="#{!managePUser.padd}">
<h:commandButton value="#{i18n.user_manager_add_user}"
action="#{managePUser.setEnablepadd}">
<f:ajax render="footeradd"/>
</h:commandButton>
</h:panelGroup>
<h:panelGroup id="adduser" rendered="#{managePUser.padd}" layout="block">
<h:panelGrid columns="2">
<h:outputText value="#{i18n.username}"/>
<h:inputText id="username" value="#{managePUser.login}"/>
<h:outputText value="#{i18n.password}"/>
<h:inputSecret id="passowrd" value="#{managePUser.password}"/>
<h:commandButton value="#{i18n.cancel_button}"
action="#{managePUser.setDisblepadd}">
<f:ajax render="footeradd"/>
</h:commandButton>
<h:commandButton value="#{i18n.submit_button}" action="#{managePUser.submit}">
<f:ajax render="footeradd userTable" execute="#this username passowrd"/>
</h:commandButton>
</h:panelGrid>
</h:panelGroup>
</h:panelGroup>
<!--</f:ajax>-->
</f:facet>
</h:dataTable>
<!--</f:ajax>-->
</h:form>
</cc:implementation>
</body>
</html>
so I using my bean in column at :
<h:commandButton id="chps" value="#{i18n.chpsqd_button}" rendered="#{!userSession.getPWRender(puser.id)}"
action="#{userSession.setPWrenerTrue(puser.id)}">
<f:ajax render="pswd chps"/>
</h:commandButton>
Question 2: what could be a better design for this situation ?
Question 3: Is it possible to listen to some events (onclick, ondbclick inside component tag ) for some component (inputSecret in my situation) if it steed as disabled=«true» ?
Thank you!
Change your scope to ViewScope, there is no need to keep UserSession class in SessionScope.
Related
This question already has an answer here:
How and when should I load the model from database for JSF dataTable
(1 answer)
Closed 1 year ago.
I have a bean that brings the list of products from the database, I can change it in onRowEdit normally, but when I do a search for the part method in the beanProd.searchProd () form it populates the datatable with related products and when I change some of them event.getObject () takes the object with an incorrect id and update incorrect product. Please HELP-ME
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<h:outputStylesheet name="a.css" library="css" />
</h:head>
<h:body>
<div id="go">
<p:panel id="basic" header="Adicionar Produto"
style="margin-bottom:20px; width:400px">
<p:panelGrid columns="4" style="margin:10px 0"/>
<h:form id="form1" >
<p:outputLabel value="Marca:" />
<td> </td>
<p:inputText id="marcacomp" value="#{beanProd.marcaProd}"
size="25" required="true" requiredMessage="#{beanMsgs.campovazio}" />
<p:message for="marcacomp" />
<br/>
<p:outputLabel value="Nome:" />
<td> </td>
<p:inputText id="nome" value="#{beanProd.nomeProd}"
size="25" required="true" requiredMessage="#{beanMsgs.campovazio}" />
<p:message for="nome" />
<br/>
<p:outputLabel value="Tamanho:" />
<td></td>
<p:inputText id="tamanho" value="#{beanProd.tamanhoProd}"
size="25" required="true" requiredMessage="#{beanMsgs.campovazio}"/>
<p:message for="tamanho" />
<br/>
<p:commandButton id="button" value="Adicionar" ajax="false"
actionListener="#{beanProd.addUser()}" update="datatable"/>
<p:messages id="messages" showDetail="true" closable="true" />
<td></td>
<td></td>
<td></td>
<br/>
</h:form>
</p:panel>
<p:panel id="basic5" header="Buscar Produtos"
style="margin-bottom:20px; width:380px">
<p:panelGrid columns="1" />
<h:form id="form10">
<p:outputLabel value="Digite a busca:" />
<br></br>
<p:inputText id="buscaprod" value="#{beanProd.busca}"
size="25" requiredMessage="#{beanMsgs.campovazio}" />
<p:commandButton id="button3" value="Buscar" ajax="false"
actionListener="#{beanProd.searchProd()}" update="datatable" />
</h:form>
</p:panel>
<h:form>
<p:commandButton id="button5" value="INVERTER TODOS MOSTRAR" ajax="false"
actionListener="#{beanProd.alterarTodos()}" update="datatable" />
</h:form>
</div>
<div id="direita">
<h:form id="form3">
<p:dataTable id="datatable" value="#{beanProd.produtos}" var="p"
editable="true" sortOrder="ascending" sortBy="#{p.id}"
paginator="true" rows="10">
<f:facet name="header">
Lista de Produtos
</f:facet>
<p:ajax event="rowEdit" listener="#{beanProd.onRowEdit}" update="datatable"/>
<p:ajax event="rowEditCancel" listener="#{beanProd.onRowCancel}" update="datatable"/>
<p:column headerText="Marca"
style="width:70px; text-align: center;">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{p.marcaProd}" />
</f:facet>
<f:facet name="input">
<p:inputText id="modelInput2" value="#{p.marcaProd}"
style="width:100%" />
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Nome"
style="width:110px; text-align: center;">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{p.nomeProd}" />
</f:facet>
<f:facet name="input">
<p:inputText id="modelInput3" value="#{p.nomeProd}"
style="width:100%" />
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Tamanho"
style="width:70px; text-align: center;">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{p.tamanhoProd}" />
</f:facet>
<f:facet name="input">
<p:inputText id="modelInput5" value="#{p.tamanhoProd}"
style="width:100%" />
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Mostrar"
style="width:50px; text-align: center;">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="Não" rendered="#{p.mostrar == 0}" />
<h:outputText value="Sim" rendered="#{p.mostrar == 1}" />
</f:facet>
<f:facet name="input">
<p:selectOneMenu id="mastrar2"
value="#{beanProd.mostrar2}"
style="height:30px; width:70px" required="false">
<f:param name="mostrar2" value="#{beanProd.mostrar2}" />
<f:selectItem itemLabel="Sim" itemValue="Sim" />
<f:selectItem itemLabel="Nao" itemValue="Nao" />
</p:selectOneMenu>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Acao" style="width:30px; text-align: center;">
<p:rowEditor editTitle="Editar" saveTitle="Salvar"
cancelTitle="Cancelar" />
<h:outputLabel id="editRow2">
<p:commandButton id="button" jax="false"
icon="ui-icon-circle-close" title="Excluir"
action="#{beanProd.deleteFromDB(p)}" update="datatable"
process="#this">
<p:confirm header="Confirmação" message="Tem certeza que deseja excluir este usuario?"
icon="pi pi-exclamation-triangle" />
</p:commandButton>
<p:confirmDialog global="true" showEffect="fade" hideEffect="fade">
<p:commandButton value="SIM" type="button"
styleClass="ui-confirmdialog-yes" />
<p:commandButton value="NÃO" type="button"
styleClass="ui-confirmdialog-no" />
</p:confirmDialog>
<p:message for="button" />
</h:outputLabel>
<p:tooltip for="editRow2" value="Excluir" showEffect="fade"
hideEffect="fade" />
</p:column>
</p:dataTable>
</h:form>
</div>
</h:body>
</html>
package Bean;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import org.primefaces.event.CellEditEvent;
import org.primefaces.event.RowEditEvent;
import DAO.DaoFactory;
import DAO.PredictDAO;
import Model.Produto;
import Model.Usuario;
#ManagedBean(name="beanProd")
#RequestScoped
public class BeanProd implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private Produto produto = new Produto();
private ArrayList<Produto> produtos;
private String marcaProd;
private String nomeProd;
private String tamanhoProd;
private String busca;
private String mostrar2;
private boolean ativo;
public BeanProd() {
}
#PostConstruct
public void init() {
buscarTodosProd();
}
public ArrayList<Produto> buscarTodosProd() {
DaoFactory factory = new DaoFactory();
factory.abrirConexao();
PredictDAO dao = factory.criarPredictDAO();
produtos = dao.buscaProdutos();
factory.fecharConexao();
return produtos;
}
public ArrayList<Produto> searchProd() {
produtos.clear();
DaoFactory factory = new DaoFactory();
factory.abrirConexao();
PredictDAO dao = factory.criarPredictDAO();
produtos = dao.buscarUmProduto(busca);
System.out.println(busca);
factory.fecharConexao();
return produtos;
}
public ArrayList<Produto> alterarTodos() {
produtos.clear();
DaoFactory factory = new DaoFactory();
factory.abrirConexao();
PredictDAO dao = factory.criarPredictDAO();
produtos = dao.alterarTodosProdutos();
factory.fecharConexao();
return produtos;
}
public void addUser() {
Produto produto = new Produto();
produto.setMarcaProd(marcaProd);
produto.setNomeProd(nomeProd);
produto.setTamanhoProd(tamanhoProd);
produto.setMostrar(1);
DaoFactory factory = new DaoFactory();
factory.abrirConexao();
PredictDAO dao = factory.criarPredictDAO();
dao.adicionarProduto(produto);
factory.fecharConexao();
produtos.add(produto);
marcaProd = "";
nomeProd = "";
tamanhoProd = "";
}
public void deleteFromDB(Produto produto) {
// FacesContext context = FacesContext.getCurrentInstance();
int id;
// int id = (Integer) event.getComponent().getAttributes().get("id2");
DaoFactory factory = new DaoFactory();
factory.abrirConexao();
PredictDAO dao = factory.criarPredictDAO();
// id =
// Integer.parseInt(context.getExternalContext().getRequestParameterMap().get("idhidden"));
try {
// Map m = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
// System.out.println(m.toString());
dao.excluirProduto(produto.getId());
produtos.remove(produto);
FacesContext.getCurrentInstance().addMessage("messages", new FacesMessage("Produto Excluido com Sucesso!"));
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
factory.fecharConexao();
}
public void onRowEdit(RowEditEvent<Produto> event) {
Produto promocao2 = new Produto();
promocao2 = (Produto) event.getObject();
System.out.println(promocao2.getId());
DaoFactory factory = new DaoFactory();
factory.abrirConexao();
PredictDAO dao = factory.criarPredictDAO();
dao.atualizarProduto(promocao2);
factory.fecharConexao();
}
public void onRowCancel(RowEditEvent event) {
System.out.println("Chamou onRowCancel!" + event.toString());
FacesMessage msg = new FacesMessage("Edit Cancelled", "" + ((Produto) event.getObject()).getId());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public boolean isAtivo() {
return ativo;
}
public void setAtivo(boolean ativo) {
this.ativo = ativo;
}
public Produto getProduto() {
return produto;
}
public void setProduto(Produto produto) {
this.produto = produto;
}
public ArrayList<Produto> getProdutos() {
return produtos;
}
public void setProdutos(ArrayList<Produto> produtos) {
this.produtos = produtos;
}
public String getMarcaProd() {
return marcaProd;
}
public void setMarcaProd(String marcaProd) {
this.marcaProd = marcaProd;
}
public String getNomeProd() {
return nomeProd;
}
public void setNomeProd(String nomeProd) {
this.nomeProd = nomeProd;
}
public String getTamanhoProd() {
return tamanhoProd;
}
public void setTamanhoProd(String tamanhoProd) {
this.tamanhoProd = tamanhoProd;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
public String getBusca() {
return busca;
}
public void setBusca(String busca) {
this.busca = busca;
}
public String getMostrar2() {
return mostrar2;
}
public void setMostrar2(String mostrar2) {
this.mostrar2 = mostrar2;
}
#Override
public String toString() {
return "BeanProd [produto=" + produto + ", produtos=" + produtos + ", marcaProd=" + marcaProd + ", nomeProd="
+ nomeProd + ", tamanhoProd=" + tamanhoProd + ", ativo=" + ativo + "]";
}
}
sorry for lack of details, it's my first post here, let's go to the details examples
all produtcts in datatable
Here are the products from the database that populate the datatable init () method with #PostConstruct annotation
When I search the form on the left with the word CREME he calls the searchProd method q populates a datatable with products that contain the word CREME
search form populate datatable search string
as you can see the datatable populated only with products containing the word CREAM
before the search I can change the product directly in the datatable normally it changes the product correctly in the database but when I do the search for a product that contains a certain word and I try to change it in the datatable it changes the product with the wrong id see before:
before
after
as you can see he should change the product with id 14 and he changes the product with id 12
wrong product changed
So, what do you think is the problem here?
Is there any way to make the change in the row along with some search filter?
I'm using JSF 2.2 and Primefaces 8.0
Sorry for my bad english.
This may happen if one of your methods updates the products list, but doesn't update the form (the view).
Start your app in the debug mode, and put a breakpoint on the setter of #{beanProd.produtos}, and find when your list is updated.
Please, help me with this, is an exercise proposed by me, which is to make an ecommerce page, surely, payments, everything, but I'm stuck on this problem., since I already use the JSP relatively, I wanted to get into the use of JSF and propose challenges, I know that it can be done directly with the Managed Bean all the interaction with the database, but I would like to add another layer to the exercise, that's where the servlet appears, and make my bean to connect between the JSF, and the Servlet, but it does not stop working, it gives me an error of null .
DP: I would like you to recommend a JavaEE book to me in depth, please, sorry for my bad English, it is not my language.
This is the servlet.
enter code here
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("---------------------Begin-----------------------------------------------");
try {
Section_Model sm = (Section_Model) request.getSession().getAttribute("section_Model");
sm.getSection().setNameAlias(request.getParameter("nameAlias"));
sm.getSection().setCodeSS((Sections) sm.findSpecific(Integer.parseInt(request.getParameter("codeSS"))));
sm.getSection().setVisible(Boolean.getBoolean(request.getParameter("visible")));
sm.create();
request.getRequestDispatcher("WEB-INF/testJSF.xhtml").forward(request, response);
} catch (Exception ex) {
Logger.getLogger(inputSections.class.getName()).log(Level.SEVERE, null, ex);
}
}
this is Managed Bean.
#Named(value = "section_Model")
#SessionScoped
public class Section_Model implements Serializable {
#Inject
private Section_Model section_Model;
#EJB
private SectionsFacadeLocal sectionsFacade;
#PersistenceContext(unitName = "ShopOnlinePU")
private EntityManager em;
#Resource
private javax.transaction.UserTransaction utx;
Sections section;
SectionsJpaController controller;
/**
* Creates a new instance of Section_Model
*/
public Section_Model() {
section= new Sections();
}
public Sections getSection() {
return section;
}
public void setSection(Sections section) {
this.section = section;
}
public void init(){
controller=new SectionsJpaController(utx, em.getEntityManagerFactory());
}
public void create () throws Exception{
init();
controller.create(section);
}
public List<Sections> select_all(){
init();
return controller.findSectionsEntities();
}
public void create2(){
sectionsFacade.create(section);
}
public List<Entity.Sections> subSections (Sections s){
return sectionsFacade.subSection(s);
}
public List<Entity.Sections> findSpecific(int id){
return sectionsFacade.findSpecificS(1);
}
public Collection<Entity.Sections> topSection (){
return sectionsFacade.TopSection();
}
public int countSection(){
return sectionsFacade.count();
}
This is JSF
<?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"
xmlns:c="http://xmlns.jcp.org/jsp/jstl/core">
<h:head>
<title>TEST Title</title>
</h:head>
<h:body>
<form action="inputSections" method="post">
<input type="text" name="nameAlias" title="NameAlias" required="true" requiredMessage="The NameAlias field is required."/>
<input type="text" name="codeSS" title="CodeSS" />
<input type="text" name="visible" title="Visible" />
<input type="submit" value="Ok"/>
</form>
<c:forEach items="#{section_Model.findSpecific(1)}" var="item">
<f:view>
<h:form>
<h:dataTable value="#{section_Model.subSections(item)}" var="items">
<h:column>
<f:facet name="header">
<h:outputText value="CodeS"/>
</f:facet>
<h:outputText value="#{items.codeS}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="NameAlias"/>
</f:facet>
<h:outputText value="#{items.nameAlias}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Visible"/>
</f:facet>
<h:outputText value="#{items.visible}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="CodeSS"/>
</f:facet>
<h:outputText value="#{items.codeSS}"/>
</h:column>
</h:dataTable>
</h:form>
</f:view>
</c:forEach>
</h:body>
</html>
The error is
GRAVE: java.lang.NullPointerException
at View.inputSections.doPost(inputSections.java:79)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:706)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:791)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1622)
at `org.apache.catalina.core.ApplicationDispatcher.doInvoke(ApplicationDispatcher.java:824)`
Good afternoon people! I'm trying to do an update through the datatable edit the Primefaces, but does not send the value of inputText upgraded to the bean. The process occurs almost correctly, the value is sent and updated, but the old value already loaded into datatable.
can anyone help me on this :)
Forgive my English. I do not speak or write very well ....
listaProduto.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:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<ui:composition template= "template.xhtml">
<ui:define name="conteudo" >
<h:form id="form">
<p:growl id="msgs" showDetail="true"/>
<p:dataTable var="prod" value="#{pBean.listaproduto}" editable="true" style="margin-bottom:20px" id="listaproduto1" >
<p:ajax event="rowEditInit" listener="#{pBean.onRowEdit}" update=":form:msgs" immediate="true" />
<p:ajax event="rowEditCancel" listener="#{pBean.onRowCancel}" update=":form:msgs" />
<p:column headerText="Id">
<h:outputText value="#{prod.id}"/>
</p:column>
<p:column headerText="Nome">
<p:cellEditor>
<f:facet name="output"><h:outputText value="#{prod.nome}"/></f:facet>
<f:facet name="input"><p:inputText value="#{prod.nome}" style="width:100%"/></f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Preço">
<p:cellEditor>
<f:facet name="output"><h:outputText value="#{prod.preco}"/></f:facet>
<f:facet name="input"><p:inputText value="#{prod.preco}" style="width:100%"/></f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Fornecedor">
<p:cellEditor>
<f:facet name="output"><h:outputText value="#{prod.fornecedor}"/></f:facet>
<f:facet name="input"><p:inputText value="#{prod.fornecedor}" style="width:100%"/></f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Categoria">
<p:cellEditor>
<f:facet name="output"><h:outputText value="#{prod.categoria}"/> </f:facet>
<f:facet name="input"><p:inputText id="cate" value="#{prod.categoria}" style="width:100%"/></f:facet>
</p:cellEditor>
</p:column>
<p:column style="width:32px">
<p:rowEditor />
</p:column>
</p:dataTable>
</h:form>
</ui:define>
</ui:composition>
</html>
ProdutoBean
package manager;
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.RowEditEvent;
import br.com.estoque.model.Produto;
import br.com.estoque.persistence.ProdutoDao;
#ManagedBean(name = "pBean")
#ViewScoped
public class ProdutoBean {
private Produto produto;
private List<Produto> listaproduto;
public ProdutoBean() {
produto = new Produto();
}
public Produto getProduto() {
return produto;
}
public void setProduto(Produto produto) {
this.produto = produto;
}
public List<Produto> getListaproduto() {
try {
listaproduto = new ProdutoDao().listar();
} catch (Exception e) {
e.printStackTrace();
}
return listaproduto;
}
public void setListaproduto(List<Produto> listaproduto) {
this.listaproduto = listaproduto;
}
public String cadastrar() {
FacesContext fc = FacesContext.getCurrentInstance();
try {
new ProdutoDao().cadastrar(produto);
fc.addMessage("formproduto", new FacesMessage(produto.getNome() + "produto cadastrado com sucesso"));
produto = new Produto();
} catch (Exception e) {
e.printStackTrace();
fc.addMessage("formproduto", new FacesMessage(produto.getNome() + "Não cadastrado"));
}
return null;
}
public void onRowEdit(RowEditEvent event) {
System.out.println(produto);
produto = ((Produto) event.getObject());
System.out.println(produto);
}
public void onRowCancel(RowEditEvent event) {
FacesMessage msg = new FacesMessage("Edit Cancelled");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
I think you should use other type of event, because rowEditInit is executing when you click pencil icon, and after edition when you click save icon is executing event rowEdit. Therefore try:
<p:ajax event="rowEdit" listener="#{pBean.onRowEdit}" update=":form:msgs"/>
Also forgive my English :)
Staff managed to solve. in fact the problem was in my listaprodutos get ... after entering an if and else, testing whether the product list was null, functioned normally.
The cool thing is, as a friend pointed out, always check the values passed by the network browser.
Hugs
I'm using JSF 2.2 in a web application and I'm having problems in the view when I use f:validateRegex and fails (because when I use immediate="true" and try to navigate to the same page again, the view isn't updated when I have a new Instance of the object in my backing bean). I was thinking richfaces has a bug (because I'm using jsf and richfaces in my main application) so I made a test code with richfaces and without richfaces (only jsf) to identify where is the error, but in both cases the view fails.
Here is my test code without richfaces (Only jsf):
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://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:c="http://xmlns.jcp.org/jsp/jstl/core">
<h:head>
<title>Mis pruebas con JSF</title>
</h:head>
<h:body>
<h:form id="lista">
<h:panelGrid id="principal">
<h:dataTable value="#{indexBB.personas}" var="persona">
<h:column>
<f:facet name="header">Activo</f:facet>
<h:selectBooleanCheckbox value="#{persona.activo}"></h:selectBooleanCheckbox>
</h:column>
<h:column>
<f:facet name="header">Nombre</f:facet>
<h:outputText value="#{persona.nombre}"></h:outputText>
</h:column>
<h:column>
<f:facet name="header">Correo</f:facet>
<h:outputText value="#{persona.correo}"></h:outputText>
</h:column>
</h:dataTable>
<h:commandButton action="#{indexBB.crearPersona}" value="Crear Persona">
</h:commandButton>
<h:commandButton action="#{indexBB.activarBoton}" value="Activar Boton">
</h:commandButton>
</h:panelGrid>
</h:form>
<h:form id="crear">
<h:panelGrid id="secundario" rendered="#{indexBB.crear}">
<h:outputText value="Activo?">
</h:outputText>
<h:selectBooleanCheckbox label="Activo" value="#{indexBB.persona.activo}">
</h:selectBooleanCheckbox>
<br></br>
<h:outputText value="Nombre"></h:outputText>
<h:inputText label="Nombre" value="#{indexBB.persona.nombre}">
</h:inputText>
<br></br>
<h:outputText value="Correo"></h:outputText>
<h:inputText label="Nombre" value="#{indexBB.persona.correo}">
<f:validateRegex
pattern="[\w\.-]*[a-zA-Z0-9_]#[\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]" />
</h:inputText>
<br></br>
<h:commandButton action="#{indexBB.guardarPersona}" value="Guardar Persona">
</h:commandButton>
<h:commandButton action="#{indexBB.cancelar}" value="Cancelar" immediate="true">
</h:commandButton>
</h:panelGrid>
</h:form>
</h:body>
</html>
Bean:
package com.kanayet.martin.view.bb;
import com.kanayet.martin.model.entity.Persona;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.inject.Named;
import javax.faces.view.ViewScoped;
#Named(value = "indexBB")
#ViewScoped
public class indexBB implements Serializable {
private Persona persona;
private List<Persona> personas;
private boolean crear;
/**
* Creates a new instance of indexBB
*/
public indexBB() {
}
#PostConstruct
public void onInit(){
personas = new ArrayList<>();
personas.add(new Persona("Martin", "martin#gmail.com", true));
personas.add(new Persona("Andrea", "andrea#gmail.com", true));
personas.add(new Persona("Camilo", "camilo#gmail.com", true));
personas.add(new Persona("Felipe", "felipe#gmail.com", true));
personas.add(new Persona("David", "david#gmail.com", true));
}
public void activarBoton() {
persona = personas.get(0);
}
public void crearPersona(){
crear = true;
persona = new Persona();
}
public void guardarPersona(){
personas.set(0, persona);
}
public void cancelar(){
}
public Persona getPersona() {
return persona;
}
public void setPersona(Persona persona) {
this.persona = persona;
}
public List<Persona> getPersonas() {
return personas;
}
public void setPersonas(List<Persona> personas) {
this.personas = personas;
}
public boolean isCrear() {
return crear;
}
public void setCrear(boolean crear) {
this.crear = crear;
}
}
Model: (Object)
package com.kanayet.martin.model.entity;
public class Persona {
private String nombre;
private String correo;
private Boolean activo;
public Persona() {
}
public Persona(String nombre, String correo, Boolean activo) {
this.nombre = nombre;
this.correo = correo;
this.activo = activo;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getCorreo() {
return correo;
}
public void setCorreo(String correo) {
this.correo = correo;
}
public Boolean getActivo() {
return activo;
}
public void setActivo(Boolean activo) {
this.activo = activo;
}
}
Here is my test code with richfaces: (Bean and Model are the same)
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://xmlns.jcp.org/jsf/html"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:rich="http://richfaces.org/rich"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
<title>Mis pruebas con RichFaces</title>
</h:head>
<h:body>
<h:form id="lista">
<a4j:outputPanel id="principal">
<rich:dataTable id="personas" value="#{indexBB.personas}"
var="persona" rows="50">
<rich:column>
<h:selectBooleanCheckbox label="Activo" value="#{persona.activo}">
</h:selectBooleanCheckbox>
</rich:column>
<rich:column>
<h:outputText value="#{persona.nombre}"></h:outputText>
</rich:column>
<rich:column>
<h:outputText value="#{persona.correo}"></h:outputText>
</rich:column>
</rich:dataTable>
<h:commandButton action="#{indexBB.crearPersona}" value="Crear Persona">
</h:commandButton>
<h:commandButton action="#{indexBB.activarBoton}" value="Activar Boton">
</h:commandButton>
</a4j:outputPanel>
</h:form>
<br></br>
<h:form id="crear">
<a4j:outputPanel id="secundario" rendered="#{indexBB.crear}">
<h:outputText value="Activo?">
</h:outputText>
<h:selectBooleanCheckbox label="Activo" value="#{indexBB.persona.activo}">
</h:selectBooleanCheckbox>
<br></br>
<h:outputText value="Nombre"></h:outputText>
<h:inputText label="Nombre" value="#{indexBB.persona.nombre}">
</h:inputText>
<br></br>
<h:outputText value="Correo"></h:outputText>
<h:inputText label="Nombre" value="#{indexBB.persona.correo}">
<f:validateRegex
pattern="[\w\.-]*[a-zA-Z0-9_]#[\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]" />
</h:inputText>
<br></br>
<h:commandButton action="#{indexBB.guardarPersona}" value="Guardar Persona">
</h:commandButton>
<h:commandButton action="#{indexBB.cancelar}" value="Cancelar" immediate="true">
</h:commandButton>
</a4j:outputPanel>
</h:form>
</h:body>
</html>
The problem is when I click "Crear Persona" button, I write for example "Nombre": Felix and "Correo": Felix and click "Guardar Persona" button so f:validateRegex fails because isn't a valid email, then click "Cancelar" because my final user doesn't know email required value (immediate="true"). Again, click "Crear Persona" button, (new object in my bean) and jsf page isn't updated, the form should be empty but it isn't, in field "Nombre" stills "Felix" value, but in my bean I have a new and empty object without values in its attributes, do you know why?
The problem is with and without richfaces (because I thought the problem could be richfaces, but it isn't), so I don't know why jsf page isn't updated if I have a new object in my bean, I used netbeans debug tool to verify but I'm right, the object that I see in my bean is different (server side new and empty object) but in my JSF page "Nombre" has "Felix" value and I want to know why it happens, and how I can resolve this problem.
Thank you so much.
The problem is that JSF maintains two representations of your model. There is the Java object, IndexBB, but there is also the component tree, the thing that keeps track of UI state.
When you fail validation, the component tree still contains the values entered. (This is a useful feature so that the user can correct the values.) You've used immediate=true to skip validation, but that doesn't reset the component tree values.
In JSF 2.2, you can use resetValues to reset component tree values:
<h:form id="crear">
<h:panelGrid id="secundario" rendered="#{indexBB.crear}">
<h:outputText value="Activo?">
</h:outputText>
<h:selectBooleanCheckbox label="Activo" value="#{indexBB.persona.activo}">
</h:selectBooleanCheckbox>
<br></br>
<h:outputText value="Nombre"></h:outputText>
<h:inputText id="nombreId" label="Nombre" value="#{indexBB.persona.nombre}">
</h:inputText>
<br></br>
<h:outputText value="Correo"></h:outputText>
<h:inputText id="correoId" label="Nombre" value="#{indexBB.persona.correo}">
<f:validateRegex
pattern="[\w\.-]*[a-zA-Z0-9_]#[\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]" />
</h:inputText>
<br></br>
<h:commandButton action="#{indexBB.guardarPersona}" value="Guardar Persona">
</h:commandButton>
<h:commandButton
action="#{indexBB.cancelar}" value="Cancelar">
<f:ajax resetValues="true" render="crear:nombreId crear:correoId"/>
</h:commandButton>
</h:panelGrid>
</h:form>
Changes:
Remove immediate=true.
Add ids to inputs you want to reset.
Add f:ajax to Cancelar button.
Add resetValues property to f:ajax and list your IDs (separate IDs with spaces, not comma).
Make sure your cancelar method actually resets persona -- the code you posted doesn't do this.
If you also want to reset the error messages, add an h:messages to the form, give it an ID, and reset it too.
See also
JSF 2.2: Reset input fields
How to skip validation when a specific button is clicked?
I'm using PrimeFaces 4.0 and Netbeans 6.9.1. I followed primefaces demo here:
DataTable Single Selection
Everything working fine expect button view. Here is my code:
Customer_list.xhtml
<p:growl id="msgs" showDetail="true" />
<h:form id="formTable">
<p:dataTable styleClass="table" id="customers" var="customer" value="#{customerBean.customer}">
<p:column>
<f:facet name="header">First Name</f:facet>
#{customer.firstName}
</p:column>
<p:column>
<f:facet name="header">Last Name</f:facet>
#{customer.lastName}
</p:column>
<p:column>
<f:facet name="header">Email</f:facet>
#{customer.email}
</p:column>
<p:column>
<f:facet name="header">DOB</f:facet>
#{customer.dob}
</p:column>
<p:column style="width:4%">
<p:commandButton id="selectButton" update=":formCreate" oncomplete="dialogCustomerCreate.show()" icon="ui-icon-search" title="Update">
<f:setPropertyActionListener value="#{customer}" target="#{customerBean.selectedCustomer}" />
</p:commandButton>
</p:column>
</p:dataTable>
</h:form>
<h:form id="formCreate">
<p:dialog header="Create New Customer" widgetVar="dialogCustomerCreate" resizable="false" id="dlgCustomerCreate"
showEffect="fade" hideEffect="explode" modal="true">
<h:panelGrid id="display" columns="2" cellpadding="4" style="margin:0 auto;">
<h:outputText value="First Name:" />
<h:outputText value="#{customerBean.selectedCustomer.firstName}" style="font-weight:bold"/>
<h:outputText value="Last Name:" />
<h:outputText value="#{customerBean.selectedCustomer.lastName}" style="font-weight:bold"/>
<h:outputText value="Email:" />
<h:outputText value="#{customerBean.selectedCustomer.email}" style="font-weight:bold"/>
<h:outputText value="DOB:" />
<h:outputText value="#{customerBean.selectedCustomer.dob}" style="font-weight:bold"/>
</h:panelGrid>
</p:dialog>
</h:form>
customerBean.java
public class customerBean {
private List<Customer> customer;
private Customer selectedCustomer;
/** Creates a new instance of customerBean */
public customerBean() {
customer = new ArrayList<Customer>();
}
public List<Customer> getCustomer() {
CustomersDao cust_dao = new CustomersDao();
customer = cust_dao.findAll();
return customer;
}
public Customer getSelectedCustomer() {
return selectedCustomer;
}
public void setSelectedCustomer(Customer selectedCustomer) {
this.selectedCustomer = selectedCustomer;
}
}
CustomersDao.java
public class CustomersDao {
public List<Customer> findAll(){
List<Customer> list_cust = null;
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
String sql = "FROM Customer";
try{
session.beginTransaction();
list_cust = session.createQuery(sql).list();
session.beginTransaction().commit();
}catch(Exception e){
session.beginTransaction().rollback();
}
return list_cust;
}
}
Hope anyone suggest me what wrong in my code. It takes me 2 days to solve it. Thanks for reading!
You need to have a converter for your Customer class:
#FacesConverter(forClass = Customer.class)
public class CustomerConverter implements Converter {
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if (value != null && !value.equals("") && !value.equals("0")) {
//find and return object from DAO
} else {
return null;
}
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
//return object id as string
}
}
1) Try removing your <h:form/>, since you're not submitting any information in that dialog;
2) Try to change your <p:commandButton update=""/> to update=":display";
3) Add process="#form" to your <p:commandButton/>;
4) If that works, i don't think you need that <h:form/>.
you did not mention the correct id for displaying popup dialog at commandButton attribute update.
<p:commandButton id="selectButton" update=":formCreate:display" oncomplete="dialogCustomerCreate.show()" icon="ui-icon-search" title="Update">
<f:setPropertyActionListener value="#{customer}" target="#{customerBean.selectedCustomer}" />
</p:commandButton>