ERROR while trying to recover data on JSP

Asked

Viewed 145 times

0

Error:

org.apache.jasper.JasperException: An exception occurred processing JSP page /ViewAluno/index.jsp at line 20

17: 
18:     <body>
19:     
20:     <input type="text" value="<%=aluno.getId()%>">
21:     
22:     <input type="text" value="<%=aluno.getLogin()%>">
23: 

JSP from Login:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>


<!DOCTYPE html>
<html lang="pt-BR">
    <head>
        <meta charset="utf-8"/>
        <title>Login-PortalEducando</title>
        <link rel="shortcut icon" href="img/favicon.ico" />
        <link rel="stylesheet" href="css/bootstrap-custom.css">
        <meta name=description content="Login">
        <meta name=viewport content="width=device-width, initial-scale=1">

    </head>

    <body>


<div class="container">
<nav class="navbar navbar-default">
  <div class="container-fluid">
    <!--RESPONSIVO PARA DISPOSITVOS TELAS MENORES -->
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="index.jsp"><img id="logoPortalEducando"src="img/PortalEducando.png" alt="Portal Educando"></a>
    </div>

    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <%@ include file="menu-publico.jsp"%>
      <!-- FIM Botão AJUDA -->
      <!--Inicio modal AJUDA-->
      <div class="modal fade" id="modalAjuda"tabindex="-1" role="dialog" aria-labelledby="MyModalLabel">
        <div class="modal-dialog" role="document">
          <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>

                <h4 class="modal-title" id="myModalLabel"><i class="fa fa-question-circle pull-left i-ajuda-modal"></i> Ajuda - Login</h4>

            </div>
            <div class="modal-body">
              <p>Local voltado para informações de ajuda realizar LOgin.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default btn-fechar-modal" data-dismiss="modal">Fechar</button>
            </div>

          </div>

        </div>
      </div>
      <!--FIM modal AJUDA-->
    </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
</nav>
            <br><br>
            <!-- CONTEUDO CENTRAL (PAINEL) -->


                 <div class="row-fluid">
            <div class="col-md-12">
            <div class="panel panel-primary panel-login">
              <div class="panel-heading title-login"><strong><span class="glyphicon glyphicon-log-in"></span> FAZER LOGIN</strong></div>  
                <div class="panel-body ">
                  <div class="form-inline">
                    <div class="form-group">
                    <form action="AutenticacaoServlet" method="post" accept-charset="utf-8">
                    <div></div>
                                                      <div class="input-group">
                                         <!-- Colocar esse select ajustado dentro da caixa  -->    

                                    <select class="form-control form-login-login" name="tipoUsuario">
                                      <option value='Aluno'>Aluno</option>
                                      <option value='Responsavel'>Responsável</option>
                                      <option value='Funcionario'>Funcionário</option>                                                                  
                                    </select>

                                <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i>
                                </span>
                                <input name="login" class="form-control form-login-login" type="text" placeholder="Login"></div>

                                <br>
                                <div class="espaco"></div>

                               <div class="input-group">
                               <span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i>
                </span> 
                               <input name="senha" class=form-control form-login-login" type="password" placeholder="Senha">  
                               </div>
                               <br><br>

                                <div class = "g-recaptcha" data-SiteKey = "6LevaR4TAAAAALT2xsSedvrxGtcXGIQlRGPFZpy5"></div><br>
                                <button type="submit" class="btn btn-primary btn-block botao-fazer-login">Fazer Login</button><br>
                         </form>       
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a id="EsqueceuSenha" href=""><u>Esqueceu a Senha?</u></a>

                     </div>   

                </div>
                </div>
                </div>




            </div>
            </div>

  </div>


</body>

<!-- INICIO RODAPE -->
<footer>

    <!-- JQUERY -->
    <script src="js/jquery.js"></script>

    <!-- BASE BOOTSTRAP-->
    <script src="js/bootstrap.min.js"></script>
    <script src="js/npm.js"></script>
    <script src="js/bootstrap-custom.js"></script>
    <script src="js/tooltip.js"></script>
    <!-- <script src ='https://www.google.com/recaptcha/api.js'></script> -->

</footer>
<!-- FIM DO RODAPE -->

Page that should appear:

<%@ page import="com.portaleducando.aluno.Aluno" %>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%
    HttpSession sessionLogin = request.getSession();
    Aluno aluno = (Aluno) request.getAttribute("UsuarioLogado");

%>
<!DOCTYPE html>
<html lang="pt-BR">

    <head>

        <title>Inicio-Portal Educando</title>
        <%@ include file="cabecalho-aluno.jsp"%>
    </head>

    <body>

    <input type="text" value="<%=aluno.getId()%>">

    <input type="text" value="<%=aluno.getLogin()%>">

    <input type="text" value="<%=aluno  .getCpf()%>">

        <nav class="navbar navbar-default">
  <div class="container-fluid">
    <!--RESPONSIVO PARA DISPOSITVOS TELAS MENORES -->
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="index.jsp"><img id="logoPortalEducando" src="../img/PortalEducando.png" alt="Portal Educando"></a>
    </div>


    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <%@ include file="menu-aluno.jsp"%>
      <!-- FIM Botão AJUDA -->

    </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
</nav>
        <div class="container">


            <div class="row-fluid">
                <!-- conteudo da esquerda -->
                <div class="col-xs-12 esquerda">
                    <div class="panel panel-primary banner-interativo teste">

                    </div>

            </div>

  </div>

  </div>

<div></div>     
</body>

<!-- INICIO RODAPE -->
<footer>

    <%@ include file="rodape-aluno.jsp"%>
    <!-- JQUERY -->
    <script src="../js/jquery.js"></script>

    <!-- BASE BOOTSTRAP-->
    <script src="../js/bootstrap.min.js"></script>
    <script src="../js/npm.js"></script>
    <script src="../js/bootstrap-custom.js"></script>
    <script src="../js/tooltip.js"></script>

</footer>
<!-- FIM DO RODAPE -->

Servlet of authentication:

package com.portaleducando.servlets;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.portaleducando.aluno.Aluno;
import com.portaleducando.aluno.ControladorAluno;
import com.portaleducando.aluno.RepositorioAlunoBDR;
import com.portaleducando.exceptions.SenhaInvalidaException;
import com.portaleducando.exceptions.UsuarioNaoEncontradoException;
import com.portaleducando.fachada.Fachada;
import com.portaleducando.funcionario.Funcionario;
import com.portaleducando.funcionario.ControladorFuncionario;
import com.portaleducando.funcionario.RepositorioFuncionarioBDR;
import com.portaleducando.professor.Professor;
import com.portaleducando.responsavel.Responsavel;

@WebServlet("/AutenticacaoServlet")
public class AutenticacaoServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public AutenticacaoServlet() {
        super();

    }

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        String login = request.getParameter("login");
        String senha = request.getParameter("senha");
        String tipoUsuario = request.getParameter("tipoUsuario");

        Fachada f = Fachada.getInstance();

    if (tipoUsuario.equals("Funcionario")) {

            try {
                 if ( f.procurarLoginFuncionario(login, senha) == true ){
                     Funcionario funcionario = f.funcionarioProcurarNome(login);

                     HttpSession sessionLogin = request.getSession();
                     sessionLogin.setAttribute("UsuarioLogado", funcionario);
                     response.sendRedirect("ViewFuncionario/index.jsp");
                 } else {
                     System.out.println("Dados Inválidos");
                     response.sendRedirect("login.jsp");
                 }
            } catch (SenhaInvalidaException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (UsuarioNaoEncontradoException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {

            }

        } else if (tipoUsuario.equals("Responsavel")) {

                try {
                    if (f.procurarLoginResponsavel(login, senha) == true ){

                        Responsavel responsavel = f.reponsavelProcurarNome(login);
                        HttpSession sessionLogin = request.getSession();
                        sessionLogin.setAttribute("UsuarioLogado", responsavel);
                        response.sendRedirect("ViewResponsavel/index.jsp");
                    } else {
                        System.out.println("Dados Inválidos");
                        response.sendRedirect("login.jsp");
                    }
                } catch (SenhaInvalidaException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (UsuarioNaoEncontradoException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }


        } else if (tipoUsuario.equals("Aluno")) { 
                try {
                    if (f.procurarLoginAluno(login, senha) == true )  {
                            //Aluno aluno = new Aluno();
                                Aluno aluno = f.alunoProcurarNome(login);

                                HttpSession sessionLogin = request.getSession();
                                sessionLogin.setAttribute("UsuarioLogado", aluno);
                                response.sendRedirect("ViewAluno/index.jsp");
                    } else {

                                    System.out.println("Dados Inválidos");
                                    response.sendRedirect("login.jsp");

                    }
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (UsuarioNaoEncontradoException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            } else if (tipoUsuario.equals("Professor")) { 
                try {
                    if (f.procurarLoginProfessor(login, senha) == true )  {
                            //Aluno aluno = new Aluno();
                                Professor professor = f.professorProcurarNome(login);

                                HttpSession sessionLogin = request.getSession();
                                sessionLogin.setAttribute("UsuarioLogado", professor);
                                response.sendRedirect("ViewProfessor/index.jsp");
                    } else {

                                    System.out.println("Dados Inválidos");
                                    response.sendRedirect("login.jsp");

                    }
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (UsuarioNaoEncontradoException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        }
}

Repositório Aluno:

package com.portaleducando.aluno;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.naming.spi.DirStateFactory.Result;

import com.portaleducando.endereco.Endereco;
import com.portaleducando.exceptions.AlunoJaCadastradoException;
import com.portaleducando.exceptions.AlunoNaoEncontradoException;
import com.portaleducando.exceptions.SenhaInvalidaException;
import com.portaleducando.exceptions.UsuarioNaoEncontradoException;
import com.portaleducando.responsavel.Responsavel;
import com.portaleducando.turma.CampoObrigatorioException;
import com.portaleducando.turma.Turma;
import com.portaleducando.util.Conexao;
import com.portaleducando.util.Database;

//Usa o implements pq o IRepositorio tem métodos abstratos e não pode ser instanciado
public class RepositorioAlunoBDR implements IRepositorioAluno {

    private Connection conectar = null;

    public RepositorioAlunoBDR() throws Exception {

        this.conectar = Conexao.getConnection(Database.MYSQL);
    }

    public void cadastrar(Aluno aluno) throws CampoObrigatorioException, SQLException {

        PreparedStatement stmt = null;
        String sql;

        sql = "INSERT INTO aluno (nome, sexo, data_nascimento, cpf, cep, cidade, estado, rua, bairro, numero,"
                + "telefone, login, senha, id_turma, id_perfil_usuario, status)"
                + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?); ";

        try {
            stmt = this.conectar.prepareStatement(sql, java.sql.Statement.RETURN_GENERATED_KEYS);
            stmt.setString(1,  aluno.getNome());
            stmt.setString(2,  aluno.getSexo());
            stmt.setString(3,  aluno.getData_nascimento());
            stmt.setString(4,  aluno.getCpf());
            stmt.setString(5,  aluno.getEndereco().getCep());
            stmt.setString(6,  aluno.getEndereco().getCidade());
            stmt.setString(7,  aluno.getEndereco().getEstado());
            stmt.setString(8,  aluno.getEndereco().getRua());
            stmt.setString(9,  aluno.getEndereco().getBairro());
            stmt.setString(10, aluno.getEndereco().getBairro());
            stmt.setString(11, aluno.getTelefone());
            stmt.setString(12, aluno.getLogin());
            stmt.setString(13, aluno.getSenha());
            stmt.setInt(14,    aluno.getTurma().getId());
            stmt.setInt(15,    aluno.getId_perfil_usuario());
            stmt.setString(16, aluno.getStatus());
            stmt.execute();

        } finally {
            stmt.close();
        }
    }

    public void atualizar(Aluno aluno) throws AlunoNaoEncontradoException, CampoObrigatorioException, SQLException {

        PreparedStatement stmt = null;
        String sql = null;

        try {
            if (aluno != null) {
                sql = "UPDATE aluno SET nome = ?, sexo = ?, data_nascimento = ?, cpf = ?, cep = ?,"
                        + "cidade = ?, estado = ?, rua = ?, bairro = ?, numero = ?, telefone = ?, login = ?,"
                        + "senha = ?, id_turma = ? " + "WHERE id = ?";

                stmt = this.conectar.prepareStatement(sql);
                stmt.setString(1,  aluno.getNome());
                stmt.setString(2,  aluno.getSexo());
                stmt.setString(3,  aluno.getData_nascimento());
                stmt.setString(4,  aluno.getCpf());
                stmt.setString(5,  aluno.getEndereco().getCep());
                stmt.setString(6,  aluno.getEndereco().getCidade());
                stmt.setString(7,  aluno.getEndereco().getEstado());
                stmt.setString(8,  aluno.getEndereco().getRua());
                stmt.setString(9,  aluno.getEndereco().getBairro());
                stmt.setString(10, aluno.getEndereco().getNumero());
                stmt.setString(11, aluno.getTelefone());
                stmt.setString(12, aluno.getLogin());
                stmt.setString(13, aluno.getSenha());
                stmt.setInt(14,    aluno.getTurma().getId());
                stmt.setInt(15,    aluno.getId());
                Integer resultado = stmt.executeUpdate();
                if (resultado == 0) {
                    throw new AlunoNaoEncontradoException();
                }
            }
        } finally {
            stmt.close();
        }
    }

    public void removerId(int id) throws AlunoNaoEncontradoException, SQLException {

        PreparedStatement stmt = null;
        String sql = null;

        try {

            sql = "UPDATE aluno SET status = 'n' WHERE id = ?";
            stmt = this.conectar.prepareStatement(sql);
            stmt.setInt(1, id);
            stmt.execute();

        } finally {
            stmt.close();
        }
    }

    //Listagem da table do aluno
    public ArrayList<Aluno> listar() throws SQLException {
        PreparedStatement stmt = null;
        ResultSet rs = null;
        ArrayList<Aluno> alunos = new ArrayList<Aluno>();
        String sql = null;

        try {

            sql = "SELECT a.id, a.nome, a.sexo, a.id_turma, DATE_FORMAT(a.data_nascimento, '%d/%m/%Y') AS data_nascimento, a.telefone, t.id, t.nome, a.status"
                    + " FROM aluno as a, turma as t"
                    + " WHERE t.id = a.id_turma and a.status = 's' ";

            stmt = this.conectar.prepareStatement(sql);
            rs = stmt.executeQuery();
            while (rs.next()) {

                Turma turma = new Turma(rs.getInt("t.id"), rs.getString("t.nome"));

                Aluno aluno = new Aluno(rs.getInt("a.id"), rs.getString("a.nome"), rs.getString("a.sexo"),
                        rs.getString("data_nascimento"), rs.getString("telefone"), turma,rs.getInt("id_turma"),rs.getString("status"));

                alunos.add(aluno);
            }

        } finally {
            stmt.close();
            rs.close();
        }
        return alunos;
    }

    //Listagem para fazer a alteração dos dados com o procurarId
    public ArrayList<Aluno> listar(String complemento) throws SQLException {

        PreparedStatement stmt = null;
        ResultSet rs = null;
        ArrayList<Aluno> alunos = new ArrayList<Aluno>();
        String sql = null;

        try {
            sql = "SELECT * FROM aluno WHERE status = 's' ";
            sql += complemento;
            stmt = this.conectar.prepareStatement(sql);
            rs = stmt.executeQuery();
            while (rs.next()) {

                Turma turma = new Turma(rs.getInt("id"),rs.getString("nome"));

                Endereco endereco = new Endereco(rs.getString("cep"), rs.getString("cidade"), rs.getString("estado"),
                        rs.getString("rua"), rs.getString("bairro"), rs.getString("numero"));

                Aluno aluno = new Aluno(rs.getInt("id"), rs.getString("nome"), rs.getString("sexo"),
                        rs.getString("data_nascimento"), rs.getString("cpf"), endereco, rs.getString("telefone"),
                        rs.getString("login"), rs.getString("senha"), turma, rs.getString("status"));

                alunos.add(aluno);
            }

        } finally {
            stmt.close();
            //rs.close();
        }
        return alunos;
    }

    public Aluno procurarId(int id) throws AlunoNaoEncontradoException, SQLException {

        String complemento = "and id = " + id;
        ArrayList<Aluno> alunos = this.listar(complemento);

        return alunos.get(0);

    }

    public Aluno procurarNome(String nome) throws AlunoNaoEncontradoException, SQLException {

        String complemento = "AND login = " + "'" + nome + "'";
        ArrayList<Aluno> alunos = this.listar(complemento);

        return alunos.get(0);

    }

    //Método para visualizar todos do aluno, turma e responsável
    public ArrayList<Aluno> visualizar(String comp) throws SQLException {
        PreparedStatement stmt = null;
        ResultSet rs = null;
        ArrayList<Aluno> alunos = new ArrayList<Aluno>();
        String sql = null;

        try {

            sql = "SELECT a.id, a.nome, a.sexo, a.id_turma, DATE_FORMAT(a.data_nascimento, '%d/%m/%Y') AS data_nascimento, a.cpf, a.cep, a.cidade, a.estado, a.rua,"
                    + "a.bairro, a.numero, a.login, a.telefone, t.id, t.nome, t.turno, resp.id, resp.nome,"
                    + "resp.sexo, DATE_FORMAT(resp.data_nascimento, '%d/%m/%Y') AS data_nascimentoR, resp.cpf,"
                    + "resp.login, resp.telefone, resp.id_aluno"
                    + " FROM aluno as a, turma as t, responsavel as resp "
                    + "WHERE t.id = a.id_turma and a.id = resp.id_aluno and a.id ";
                sql += comp;

                stmt = this.conectar.prepareStatement(sql);
                rs = stmt.executeQuery();
                while (rs.next()) {

                    Endereco endereco = new Endereco(rs.getString("a.cep"), rs.getString("a.cidade"), rs.getString("a.estado"),
                            rs.getString("a.rua"), rs.getString("a.bairro"), rs.getString("a.numero"));

                    Turma turma = new Turma(rs.getInt("t.id"), rs.getString("t.nome"), rs.getString("t.turno"));

                    Responsavel responsavel = new Responsavel(rs.getInt("resp.id"),rs.getString("resp.nome"),rs.getString("resp.sexo"),
                            rs.getString("data_nascimentoR"), rs.getString("resp.cpf"), rs.getString("resp.telefone"),
                            rs.getInt("resp.id_aluno"),rs.getString("resp.login"));

                    Aluno aluno = new Aluno(rs.getInt("a.id"), rs.getString("a.nome"),rs.getString("a.sexo"), rs.getString("data_nascimento"),
                            rs.getString("a.cpf"), endereco, rs.getString("a.telefone"),
                            rs.getString("a.login"), rs.getInt("a.id_turma"), turma, responsavel);

                alunos.add(aluno);
            }

        } finally {
            stmt.close();
            //rs.close();
        }
        return alunos;
    }

    public Aluno visualizarDados(int id) throws AlunoNaoEncontradoException, SQLException {

        String comp = " = " +  id;
        ArrayList<Aluno> alunos = this.visualizar(comp);

        return alunos.get(0);

    }

    @Override
    public boolean procurarLoginAluno(String login, String senha) throws SenhaInvalidaException, UsuarioNaoEncontradoException, SQLException {
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try{
            String sql ="select count(*) as existe from aluno where login = ? and senha = ?";
            stmt = this.conectar.prepareStatement(sql);
            stmt.setString(1, login);
            stmt.setString(2, senha);
            rs = stmt.executeQuery();
            rs.next();
            if(rs.getInt("existe") == 0){
                return false;

            }else {
                return true;
            }
        }finally{

        }
    }

}
  • Aluno aluno = (Aluno) request.getAttribute("UsuarioLogado"); -> Are you sure this won’t come back null then giving a NullPointerException in the <%=aluno.getId()%>"?

  • I don’t know, I’m a beginner in the area. I’m trying to get the data of the logged-in user back on the screen.

  • And if there is no logged in user, what should happen?

  • In addition, declaring the encoding "ISO-8859-1" at first, while declaring "utf-8" within the <head> is ask to have serious problems with accented characters.

  • I just added the authentication Servlet

  • The error occurs as if it had null values within the attributes I try to rescue.

  • What’s in the methods f.procurarLoginAluno(login, senha) and f.alunoProcurarNome(login)?

  • In this case, within the repository?

  • Yes. How is the code of these methods?

  • added the repository code

  • Right, but the method f.alunoProcurarNome(login) is not in the code you just entered. I suspect the problem is in this method.

  • I can’t possibly identify the error.

Show 7 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.