Hello everyone. I am currently experiencing a problem with prime faces which is a library of visual Java components.
The problem I am having is the following: In the login screen of my system, there is a commandButton to call a dialog that contains the form to register new users. Within this form, there is a selectOneMenu that must be loaded with the States of Brazil for the user to choose. The point is that this selectOneMenu is not loading. When I click on it, it is empty.
I want to let you know that I have tried to remove the selectOneMenu from the dialog and put it in the form of the page, but it still gives the same problem.
So, I would like to ask you for help. I am sending the codes of the main components related to the login screen
Main.xhtml (system login page)
<ui:composition template="/WEB-INF/template/LayoutMain.xhtml"
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"
xmlns:a="http://xmlns.jcp.org/jsf/passthrough">
<h:head>
<f:facet name="first">
<meta name="viewport" content="width-device-width, inicial-scale=1"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</f:facet>
<title><ui:insert name="titulo">Sistema de Rastreamento de Gado</ui:insert></title>
<h:outputScript name="locale-primefaces.js" library="js" />
<h:outputStylesheet library="css" name="sistema.css" />
</h:head>
<ui:define name="titulo">Rastrbov</ui:define>
<ui:define name="corpo">
<f:metadata>
<f:viewParam name="Dummy" />
<f:event listener="#{loginBean.preRender}" type="preRenderView"></f:event>
</f:metadata>
<h:form prependId="false">
<header class="main-topbar">
<h:link outcome="/Home">
<h:graphicImage library="images" name="Rastrbov.png" styleClass="rastrbovPng" />
</h:link>
<div style="float: right;">
<div style="float: left; line-height: 70px; margin-right: 30px;">
<p:inputText size="20" id="j_username" value="#{loginBean.nome}"
a:placeholder="📧Login" />
</div>
<div style="float: left; line-height: 70px; margin-right: 30px;">
<p:password size="20" id="j_password"
a:placeholder="🔑Senha" />
</div>
<div style="float: left; line-height: 70px; margin-right: 10px;">
<p:commandButton value="Entrar" action="#{loginBean.login}"
ajax="false" styleClass="botaoLogin"/>
</div>
<div style="line-height: 0px; margin-right: 10px;" >
<p:commandLink
styleClass="esqSenha"
value="Esqueceu sua senha?"
onclick="PF('varDialogResetarSenha').show()" type="button" />
</div>
</div>
</header>
</h:form>
<h:form prependId="false">
<p:panel styleClass="cadastrese" style="width:400px">
<p:messages id="messages" autoUpdate="true" closable="true" />
<br />
<br />
<p:outputLabel value="Seja bem-vindo ao sistema RastrBov"
style="font-weight:bold;font-size:40px" />
<p:commandButton value="Cadastre-se" size="50"
onclick="PF('dlgCadastrarUsuario').show()"
styleClass="botaoCadastrar"/>
</p:panel>
<p:dialog header="Cadastro de usuário" widgetVar="dlgCadastrarUsuario"
modal="true" height="400">
<h:form id="frmCadastroUser" prependId="false">
<p:toolbar style="margin-top: 20px">
<p:toolbarGroup >
<p:button value="Novo" outcome="/usuario/CadastroUsuario"
disabled="#{cadastroUsuarioBean.editando}" />
<p:commandButton value="Salvar" id="botaoSalvar"
action="#{cadastroUsuarioBean.salvar}" update="@form" />
</p:toolbarGroup>
</p:toolbar>
<p:panel>
<p:panelGrid columns="2" id="painel"
style="width: 100%; margin-top: 20px" columnClasses="rotulo, campo">
<p:outputLabel value="Estado" for="estado2" />
<p:selectOneMenu id="estado2" style="width:52%"
value="#{LoginBean.usuario.estado}" label="Estado"
required="true" requiredMessage="Informe o estado de residência">
<f:selectItem itemLabel="" noSelectionOption="true" />
<f:selectItems value="#{LoginBean.listEstados}"
var="estado" itemValue="#{estado}"
itemLabel="#{estado.estado_sigla}" />
<!-- <p:ajax listener="#{cadastroUsuarioBean.carregarCidades}" update="cidade" /> -->
</p:selectOneMenu>
</p:panelGrid>
</p:panel>
</h:form>
</p:dialog>
</h:form>
<p:separator style="margin-top:300px" />
<footer> </footer>
</ui:define>
In the final part of the code, I declare the dialog. Inside the dialog there is only the state selectOneMenu because I removed the other components for easy viewing.
LoginBean.java (The bean that handles the actions performed on the Main.xhtml screen)
package com.sisRastrbov.controller;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.enterprise.context.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sisRastrbov.model.Estado;
import com.sisRastrbov.model.Usuario;
import com.sisRastrbov.repository.EstadosRep;
import com.sisRastrbov.util.jsf.FacesUtil;
@Named
@SessionScoped
public class LoginBean implements Serializable {
private static final long serialVersionUID = 1L;
@Inject
private FacesContext facesContext;
@Inject
private HttpServletRequest request;
@Inject
private HttpServletResponse response;
@Inject
private EstadosRep estadosRep;
private Usuario usuario;
private String nome;
private Estado estado;
private List<SelectItem> listEstados;
public void login() throws ServletException, IOException{
RequestDispatcher dispatcher = request.getRequestDispatcher("/j_spring_security_check");
dispatcher.forward(request, response);
facesContext.responseComplete();
}
public void preRender(){
if("true".equals(request.getParameter("invalid"))){
FacesUtil.addErrorMessage("Usuário ou senha invalido!");
}
System.out.println("estou carregando estados");
listEstados = new ArrayList<SelectItem>();
List<Estado> estados = estadosRep.raizes();
for (Estado e : estados) {
SelectItem item = new SelectItem();
item.setLabel(e.getEstado_sigla());
item.setValue(e);
listEstados.add(item);
System.out.println(e);
}
if (this.estado != null) {
estados = estadosRep.raizes();
}
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public EstadosRep getEstadosRep() {
return estadosRep;
}
public void setEstadosRep(EstadosRep estadosRep) {
this.estadosRep = estadosRep;
}
public List<SelectItem> getListEstados() {
return listEstados;
}
public void setListEstados(List<SelectItem> listEstados) {
this.listEstados = listEstados;
}
public Estado getEstado() {
return estado;
}
public void setEstado(Estado estado) {
this.estado = estado;
}
public Usuario getUsuario() {
return usuario;
}
public void setUsuario(Usuario usuario) {
this.usuario = usuario;
}
}
In this bean, the key is the preRender method that is used to load the selectonemenu of states at the time that Main.xhtml is started.
package com.sisRastrbov.repository;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import com.sisRastrbov.model.Estado;
public class EstadosRep implements Serializable {
private static final long serialVersionUID = 1L;
@Inject
private EntityManager manager;
public Estado porSigla(String estado_sigla) {
return manager.find(Estado.class, estado_sigla);
}
public List<Estado> raizes(){
return manager.createQuery("from Estado",Estado.class).getResultList();
}
public List<Estado> listarEstado() {
List<Estado> estados = new ArrayList<Estado>();
estados= manager.createQuery("from Estado", Estado.class).getResultList();
return estados;
}
}
State.java (State class declaration. It is used to create the State table in the database)
package com.sisRastrbov.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
@Entity
@Table(name = "estado")
public class Estado implements Serializable {
private static final long serialVersionUID = 1L;
private String estado_sigla;
private String estado_nome;
@Id
@Column(nullable = false, length = 2)
public String getEstado_sigla(){
return estado_sigla;
}
public void setEstado_sigla(String estado_sigla){
this.estado_sigla = estado_sigla;
}
@NotNull
@Column(nullable = false, length = 50)
public String getEstado_nome(){
return estado_nome;
}
public void setEstado_nome(String estado_nome){
this.estado_nome = estado_nome;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((estado_sigla == null) ? 0 : estado_sigla.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Estado other = (Estado) obj;
if (estado_sigla == null) {
if (other.estado_sigla != null)
return false;
} else if (!estado_sigla.equals(other.estado_sigla))
return false;
return true;
}
}
I hope for answers and thank you all.