Olá a todos.
Estou com um problema com o JSF.
Logo após inserir no banco (ele realmente insere, eu vi pelo debug e pelo console do MySQL), a página é redirecionada para a página de listar (até aí tudo bem).
Mas assim que entra na página, aparece a mensagem que foi excluído com sucesso do banco, como se eu chamasse um método que eu não estou chamando.
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE composition 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"
template="./../modeloPrincipal.xhtml"
xmlns:p="http://primefaces.prime.com.tr/ui"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">
<ui:define name="content">
<p:growl id="growl" showDetail="true" life="3000" />
<h:form id="cadastro">
<h:panelGrid columns="2" cellpadding="5">
<h:outputText value="Nome do Aluno:" />
<h:inputText id="nome" title="Digite o nome do aluno" value="#{alunoBean.nome}"/>
<h:outputText value="Sobrenome do Aluno:" />
<h:inputText id="sobrenome" title="Digite o sobrenome do aluno" value="#{alunoBean.sobrenome}"/>
<h:outputText value="Email do Aluno:" />
<h:inputText id="email" title="Digite o email do aluno" value="#{alunoBean.email}">
<f:validator validatorId="emailValidator"/>
</h:inputText>
<h:outputText value="Sexo do Aluno:" />
<h:selectOneMenu value="#{alunoBean.sexo}">
<f:selectItem itemLabel="Masculino" itemValue="M"/>
<f:selectItem itemLabel="Feminino" itemValue="F"/>
</h:selectOneMenu>
<h:outputText value="Peso do Aluno:" />
<h:inputText id="peso" title="Digite o peso do aluno" value="#{alunoBean.peso}"/>
<h:outputText value="Data de Nascimento do Aluno:" />
<h:inputText id="dataNascimento" title="Digite a data de nascimento do aluno" value="#{alunoBean.nascimento}" converterMessage="Data inválida. Use o formato dd/MM/yyyy">
<f:converter converterId="alunoConverter"/>
<f:convertDateTime pattern="dd/MM/yyyy"></f:convertDateTime>
</h:inputText>
<h:commandButton action="#{alunoBean.criarAluno()}" value="Cadastrar" />
</h:panelGrid>
</h:form>
</ui:define>
</ui:composition>
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package sonic.action.aluno;
import javax.enterprise.context.SessionScoped;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import sonic.action.grupo.GrupoBean;
import sonic.action.professor.ProfessorBean;
import sonic.action.usuario.UsuarioBean;
import sonic.model.entities.Aluno;
import sonic.model.entities.Usuario;
import sonic.model.repositories.ConnectionFactory;
/**
*
* @author Felipe
*/
@ManagedBean
@SessionScoped
public class AlunoBean implements Serializable {
private Integer idaluno;
private String nome;
private String sobrenome;
private String email;
private String sexo;
private int peso;
private Date nascimento;
private Aluno aluno = new Aluno();
public String criarAluno() {
String retorno = "cria";
FacesMessage msg;
try {
if (verificaAluno(email)) {
msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Aluno já existe", "");
} else {
Connection con = ConnectionFactory.GetConnection();
String sql = "INSERT INTO Aluno(nome, sobrenome, email, sexo, peso, nascimento, idprofessor) VALUES (?,?,?,?,?,?,?); ";
System.out.println(nome);
System.out.println(sobrenome);
System.out.println(email);
System.out.println(sexo);
System.out.println(peso);
System.out.println(nascimento.getClass());
// cria um preparedStatement
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setString(1, nome);
stmt.setString(2, sobrenome);
stmt.setString(3, email);
stmt.setString(4, sexo);
stmt.setInt(5, peso);
stmt.setDate(6, new java.sql.Date(nascimento.getTime()));
stmt.setInt(7, obterProfessor());
stmt.execute();
stmt.close();
con.close();
retorno = "listar";
msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Aluno Cadastrado com Sucesso", "");
}
FacesContext.getCurrentInstance().addMessage(null, msg);
return retorno;
} catch (SQLException ex) {
Logger.getLogger(UsuarioBean.class.getName()).log(Level.SEVERE, null, ex);
msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Ocorreu algum erro", "");
FacesContext.getCurrentInstance().addMessage(null, msg);
return retorno;
}
}
public String editarAluno() {
FacesMessage msg;
String retorno = "listar";
try {
Connection con = ConnectionFactory.GetConnection();
String sql = "UPDATE Aluno SET nome = ?, sobrenome = ?, email = ?, sexo = ?, peso=? WHERE email = ?";
// cria um preparedStatement
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setString(1, aluno.getNome());
stmt.setString(2, aluno.getSobrenome());
stmt.setString(3, aluno.getEmail());
stmt.setString(4, aluno.getSexo());
stmt.setInt(5, aluno.getPeso());
stmt.setString(6, aluno.getEmail());
stmt.executeUpdate();
//fecha a conexão
stmt.close();
con.close();
msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Aluno Editado com Sucesso", "");
FacesContext.getCurrentInstance().addMessage(null, msg);
return retorno;
} catch (SQLException ex) {
Logger.getLogger(ProfessorBean.class.getName()).log(Level.SEVERE, null, ex);
return retorno;
}
}
public String deletarAluno() {
String retorno = "listar";
FacesMessage msg;
try {
Connection con = ConnectionFactory.GetConnection();
String sql = "DELETE FROM Aluno WHERE email = ?";
// cria um preparedStatement
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setString(1, email);
stmt.execute();
//fecha a conexão
stmt.close();
con.close();
msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Aluno Removido com Sucesso", "");
FacesContext.getCurrentInstance().addMessage(null, msg);
return retorno;
} catch (SQLException ex) {
Logger.getLogger(ProfessorBean.class.getName()).log(Level.SEVERE, null, ex);
return retorno;
}
}
public List<Aluno> listar() {
ArrayList<Aluno> alunos = new ArrayList<Aluno>();
try {
Connection con = ConnectionFactory.GetConnection();
String sql = "SELECT * FROM Aluno where idprofessor = ?";
// cria um preparedStatement
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setInt(1, obterProfessor());
// executa o select
ResultSet rs = stmt.executeQuery();
// itera no ResultSet
while (rs.next()) {
Aluno a = new Aluno();
a.setNome(rs.getString("nome"));
a.setSobrenome(rs.getString("sobrenome"));
a.setPeso(rs.getInt("peso"));
a.setSexo(rs.getString("sexo"));
a.setEmail(rs.getString("email"));
a.setNascimento(rs.getDate("nascimento"));
a.setIdaluno(rs.getInt("idaluno"));
alunos.add(a);
}
//fecha a conexão
stmt.close();
con.close();
return alunos;
} catch (SQLException ex) {
Logger.getLogger(GrupoBean.class.getName()).log(Level.SEVERE, null, ex);
return alunos;
}
}
public boolean verificaAluno(String email) {
boolean retorno = false;
try {
Connection con = ConnectionFactory.GetConnection();
String sql = "SELECT * FROM Aluno WHERE email = ?";
// cria um preparedStatement
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setString(1, email);
// executa o select
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
if (rs.getString("email").equals(email)) {
retorno = true;
break;
}
}
//fecha a conexão
stmt.close();
con.close();
return retorno;
} catch (SQLException ex) {
Logger.getLogger(UsuarioBean.class.getName()).log(Level.SEVERE, null, ex);
return retorno;
}
}
public int obterProfessor() {
int retorno = 0;
FacesContext context = FacesContext.getCurrentInstance();
String usuario = (String) context.getExternalContext().getSessionMap().get("user");
try {
Connection con = ConnectionFactory.GetConnection();
String sql = "SELECT * FROM professor WHERE nome = ?";
// cria um preparedStatement
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setString(1, usuario);
// executa o select
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
retorno = rs.getInt("idprofessor");
}
//fecha a conexão
stmt.close();
con.close();
return retorno;
} catch (SQLException ex) {
Logger.getLogger(UsuarioBean.class.getName()).log(Level.SEVERE, null, ex);
return retorno;
}
}
public String obterNomeProfessor(int idprofessor){
String retorno = null;
try {
Connection con = ConnectionFactory.GetConnection();
String sql = "SELECT * FROM professor WHERE idprofessor = ?";
// cria um preparedStatement
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setInt(1, idprofessor);
// executa o select
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
retorno = rs.getString("nome");
}
//fecha a conexão
stmt.close();
con.close();
return retorno;
} catch (SQLException ex) {
Logger.getLogger(UsuarioBean.class.getName()).log(Level.SEVERE, null, ex);
return retorno;
}
}
public Aluno getAluno() {
return aluno;
}
public void setAluno(Aluno aluno) {
this.aluno = aluno;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getIdaluno() {
return idaluno;
}
public void setIdaluno(Integer idaluno) {
this.idaluno = idaluno;
}
public Date getNascimento() {
return nascimento;
}
public void setNascimento(Date nascimento) {
this.nascimento = nascimento;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public int getPeso() {
return peso;
}
public void setPeso(int peso) {
this.peso = peso;
}
public String getSexo() {
return sexo;
}
public void setSexo(String sexo) {
this.sexo = sexo;
}
public String getSobrenome() {
return sobrenome;
}
public void setSobrenome(String sobrenome) {
this.sobrenome = sobrenome;
}
/**
* Creates a new instance of AlunoBean
*/
public AlunoBean() {
}
}
A exclusão ocorre logo após a linha 179 do managed bean.
Aparecem as mensagens na tela de listar
Essa é a minha tela de listar:
Aluno Cadastrado com Sucesso
Aluno Removido com Sucesso
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE composition 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"
template="./../modeloPrincipal.xhtml"
xmlns:p="http://primefaces.prime.com.tr/ui"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">
<ui:define name="content">
<h:form prependId="false">
<p:dataTable id="dataTable" var="aluno" value="#{alunoBean.listar()}" emptyMessage="Não há alunos cadastrados para o professor logado">
<p:column id="editarExcluirHeader">
<f:facet name="header">
<h:outputText value="Editar" />
</f:facet>
<h:commandLink id="editarLink" action="editar">
<f:setPropertyActionListener target="#{alunoBean.aluno}" value="#{aluno}" />
<h:graphicImage id="editar" value="./../resources/images/edit_pencil.gif" width="16" height="16" />
</h:commandLink>
<!--<h:commandLink id="excluirLink" action="#{alunoBean.deletarAluno()}">
<f:setPropertyActionListener target="#{alunoBean.email}" value="#{aluno.email}" />
<h:graphicImage id="excluir" value="./../resources/images/trash.gif" width="16" height="16" />
</h:commandLink>-->
</p:column>
<p:column id="nomeHeader" sortBy="#{aluno.nome}">
<f:facet name="header">
<h:outputText value="Nome" />
</f:facet>
<h:outputText value="#{aluno.nome}" />
</p:column>
<p:column id="sobrenomeHeader" sortBy="#{aluno.sobrenome}">
<f:facet name="header">
<h:outputText value="Sobrenome" />
</f:facet>
<h:outputText value="#{aluno.sobrenome}" />
</p:column>
<p:column id="emailHeader" sortBy="#{aluno.email}">
<f:facet name="header">
<h:outputText value="Email" />
</f:facet>
<h:outputText value="#{aluno.email}" />
</p:column>
<p:column id="pesoHeader" sortBy="#{aluno.peso}">
<f:facet name="header">
<h:outputText value="Peso" />
</f:facet>
<h:outputText value="#{aluno.peso}" />
</p:column>
<p:column id="sexoHeader" sortBy="#{aluno.sexo}">
<f:facet name="header">
<h:outputText value="Sexo" />
</f:facet>
<h:outputText value="#{aluno.sexo}" />
</p:column>
<p:column id="nascimentoHeader" sortBy="#{aluno.nascimento}">
<f:facet name="header">
<h:outputText value="Data de Nascimento" />
</f:facet>
<h:outputText value="#{aluno.nascimento}" />
</p:column>
</p:dataTable>
</h:form>
</ui:define>
</ui:composition>
Não ocorrem exceções no console do glassfish.
Desculpem se o código está bagunçado :D
Sabem o que pode ser isso? Estou desde ontem tentando e não consigo...
Agradeço a ajuda de todos!
Acabei misturando tudo. Vou refatorar quando funcionar. Prometo.