Porque o Nome é null?

3 respostas
Jrmanzini

nao consigo encontrar o problema nomeAluno entra null no BD…

classe aluno

public class Aluno {
private int idAluno;
private String nomeAluno;
private int idadeAluno;
private String anoAluno;
private String obsAluno;
private Float mediaAluno;
private String foneAluno;

    public Aluno() {

    }

     public String getAnoAluno() {
        return anoAluno;
    }

    public void setAnoAluno(String anoAluno) {
        this.anoAluno = anoAluno;
    }

    

    public String getFoneAluno() {
        return foneAluno;
    }

    public void setFoneAluno(String foneAluno) {
        this.foneAluno = foneAluno;
    }

    public int getIdAluno() {
        return idAluno;
    }

    public void setIdAluno(int idAluno) {
        this.idAluno = idAluno;
    }

    public int getIdadeAluno() {
        return idadeAluno;
    }

    public void setIdadeAluno(int idadeAluno) {
        this.idadeAluno = idadeAluno;
    }

    public Float getMediaAluno() {
        return mediaAluno;
    }

    public void setMediaAluno(Float mediaAluno) {
        this.mediaAluno = mediaAluno;
    }

    public String getNomeAluno() {
        return nomeAluno;
    }

    public void setNomeAluno(String nomeAluno) {
        this.nomeAluno = nomeAluno;
    }

    public String getObsAluno() {
        return obsAluno;
    }

    public void setObsAluno(String obsAluno) {
        this.obsAluno = obsAluno;
    }
public String mostraNomeAluno(){
    return nomeAluno;
}

}

ALuno DAO

public class AlunoDAO {

    public static boolean save(Aluno aluno) {

        String sql = "insert into aluno (nomeAluno,anoAluno,idadeAluno,obsAluno,mediaAluno,foneAluno)values(?,?,?,?,?,?)";
        try {
            PreparedStatement pstm = (PreparedStatement) new Conexao().getConexao().prepareStatement(sql);
            pstm.setString(1, aluno.getNomeAluno());
            pstm.setString(2, aluno.getAnoAluno());
            pstm.setInt(3, aluno.getIdadeAluno());
            pstm.setString(4, aluno.getObsAluno());
            pstm.setFloat(5, aluno.getMediaAluno());
            pstm.setString(6, aluno.getFoneAluno());

            pstm.executeUpdate();
            return true;

        } catch (Exception e) {
            System.out.println("Erro ao inserir o Aluno\n" + e);
            return false;
        }
    }

    public boolean delete(int alu) {
        String sql = "DELETE aluno from aluno WHERE idAaluno = ?" + alu;
        Aluno aluno;
        aluno = new Aluno();
        try {
            PreparedStatement pstm = (PreparedStatement) new Conexao().getConexao().prepareStatement(sql);
            pstm.setInt(1, aluno.getIdAluno());
            pstm.executeUpdate();
            System.out.println("Excluido com sucesso");
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static boolean update(Aluno aluno) {
        String sql = "UPDATE aluno SET nomeAluno = ?, anoAluno = ?, idadeAluno= ?, obsAluno = ?, mediaAluno = ? , foneAluno =? WHERE idAluno = ?";
        try {
            PreparedStatement pstm = (PreparedStatement) new Conexao().getConexao().prepareStatement(sql);
            pstm.setInt(1, aluno.getIdAluno());
            pstm.setString(2, aluno.getNomeAluno());
            pstm.setString(3, aluno.getAnoAluno());
            pstm.setInt(4, aluno.getIdadeAluno());
            pstm.setString(5, aluno.getObsAluno());
            pstm.setFloat(6, aluno.getMediaAluno());
            pstm.setString(7, aluno.getFoneAluno());
            pstm.executeUpdate();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static Aluno recuperate(int codigo) {
        Aluno alu;
        String sql = "SELECT nomeAluno,anoAluno,idadeAluno,obsAluno,mediaAluno,foneAluno from aluno WHERE idAluno = " + codigo;
        try {
            Statement stm = new Conexao().getConexao().createStatement();
            ResultSet rs = stm.executeQuery(sql);
            if (rs.next()) {
                alu = new Aluno();
                alu.setNomeAluno(rs.getString("nomeAluno"));
                alu.setAnoAluno(rs.getString("anoAluno"));
                alu.setIdadeAluno(rs.getInt("idadeAluno"));
                alu.setObsAluno(rs.getString("obsAluno"));
                alu.setMediaAluno(rs.getFloat("mediaAluno"));
                alu.setFoneAluno(rs.getString("foneAluno"));
                return alu;
            } else {
                return null;
            }
        } catch (Exception e) {
            return null;
        }
    }

    public static List<Aluno> recuperateAll() {
        List<Aluno> lista = new ArrayList<Aluno>();
        String sql;
        Aluno alu;
        
        sql = "SELECT idAluno, nomeAluno,anoAluno,idadeAluno,obsAluno,mediaAluno,foneAluno from aluno ORDER BY nomeAluno";
        try {
            Statement stm = (Statement) new Conexao().getConexao().createStatement();
            ResultSet rs = (ResultSet) stm.executeQuery(sql);
            while (rs.next()) {
                alu = new Aluno();
                alu.setIdAluno(Integer.valueOf(rs.getString("idAluno")));
                alu.setNomeAluno(rs.getString("nomeAluno"));
                alu.setAnoAluno(rs.getString("anoAluno"));
                alu.setIdadeAluno(Integer.valueOf(rs.getString("idadeAluno")));
                alu.setObsAluno(rs.getString("obsAluno"));
                alu.setMediaAluno(Float.parseFloat(rs.getString("mediaAluno")));
                alu.setFoneAluno(rs.getString("foneAluno"));
               lista.add(alu);
            }

        } catch (Exception e) {
            lista = null;
            System.out.println("Erro ao montar lista de Clientes\nErro:\n" + e);
        }
        return lista;
    }


}

Servlet

public class srvCadastraAlunos extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        String  nome, ano, obs, fone, idade, media;

        nome = request.getParameter("txtNomeAluno");
        idade = request.getParameter("txtIdade");
        ano = request.getParameter("txtAno");
        obs = request.getParameter("txtObs");
        media = request.getParameter("txtMedia");
        fone = request.getParameter("txtFone");

        Aluno alu;
        alu = new Aluno();
        alu.setNomeAluno(nome);
        alu.setIdadeAluno(Integer.valueOf(idade));
        alu.setAnoAluno(ano);
        alu.setObsAluno(obs);
        alu.setMediaAluno(Float.valueOf(media));
        alu.setFoneAluno(fone);

        boolean result = false;

        result = AlunoDAO.save(alu);

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {

            out.println("<html>");
            out.println("<head>");
            out.println("<title>Resultado da Inclusão</title>");
            out.println("</head>");
            out.println("<body>");
            if (result) {
                out.println("<h1>Salvo com Sucesso!</h1>");
            } else {
                out.println("<h1>Erro ao Salvar Cliente.</h1>");
            }
            out.println("<a href='index.jsp'>VOLTAR</a>");
            out.println("</body>");
            out.println("</html>");

        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}

não consigo achar onde esta o problema… a página html esta aqui

<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form name="form1" method="post" action="srvCadastraAlunos">
  <table width="25%" border="0" cellspacing="0" cellpadding="0">
    <tr>
      <td width="41%" height="20">Nome</td>
      <td width="59%"><input name="txtNome " type="text" id="txtNomeAluno"></td>
    </tr>
    <tr>
      <td>Idade</td>
      <td><input name="txtIdade" type="text" id="txtIdade"></td>
    </tr>
    <tr>
      <td>Ano</td>
      <td><input name="txtAno" type="text" id="txtAno"></td>
    </tr>
    <tr>
      <td>Observação</td>
      <td><input name="txtObs" type="text" id="txtObs"></td>
    </tr>
    <tr>
      <td>Média</td>
      <td><input name="txtMedia" type="text" id="txtMedia"></td>
    </tr>
    <tr>
      <td>Fone</td>
      <td><input name="txtFone" type="text" id="txtFone"></td>
    </tr>
    <tr>
      <td><input name="Cadastrar" type="submit" id="Cadastrar" value="Cadastrar"></td>
      <td>&nbsp;</td>
    </tr>
  </table>
</form>
</body>
</html>

obrigado

3 Respostas

sergiolopes

Olá!

Na página HTML, linha 16, o atributo name:

&lt;input name="txtNomeAluno" type="text" id="txtNomeAluno"&gt;

E algumas dicas de boas práticas (não que esteja errado):

  • Evite colocar os nomes dos atributos de Aluno como “nomeAluno”, “idadeAluno” etc. Eles já estão dentro da classe Aluno, “nome”, “idade” etc devem ser suficiente.

  • O nome da classe que abre a conexão não deveria se chamar Conexao (ela não é a Conexao, ela é quem abre a Conexao). Nomes mais interessantes: CriadoraDeConexoes ou FabricaDeConexoes ou algo do tipo.

Abraços

  • Cuidado que você não está fechando a Connection em nenhum momento, isso pode trazer problemas.
Jrmanzini

Valeu Sérgio usarei essas práticas, abraços.

leomorais

Outra dica:

Evite mostrar resultados dentro do Servlet, isto nao é nada elegante… um servlet deve ser utilizado como um Controller… ao invés de imprimir o resultado dentro do servlet, redirecione o resultado para uma outra pagina com: getRequestDispatcher(“pagina.jsp”).forward(request,response)

:wink:

Criado 5 de dezembro de 2010
Ultima resposta 5 de dez. de 2010
Respostas 3
Participantes 3