Why does my Drivermanager return null Pointer?

Asked

Viewed 176 times

3

Postgresql 9.4

  1. I execute my class Noticias().
  2. Within the method public static void main() class Noticias() a method is called getConexao();
  3. When I execute pagecontroller?=p=noticias in the browser it returns to me java.lang.NullPointerException.
  4. When I run the class Noticias() in Eclipse it does not return a null pointer and makes connection to the database without any error.

Obs.: Inside the directory Webcontent/WEB-INF/lib/ I am with the lib postgresql-9.4-1201.jdbc4.jar but still when I use my class Noticias() by the browser is not connected to the database, my Tomcat server is running through the Eclipse IDE.

public class PageController extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public PageController() {
       super();
    }

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("Chamou o metodo GET");

    String pagina = request.getParameter("p");


    if (pagina.equals("noticias")){
        Noticias noticias = new Noticias();
        List<Noticias> lista = noticias.getNoticias();
        request.setAttribute("noticias", lista);
        RequestDispatcher saida = request.getRequestDispatcher("noticias.jsp");
        saida.forward(request, response);
    }

}

Follows class Noticias():

public class Noticias{

int grid;
String topico;
String conteudo;
int usuario;
Date data;

public Noticias(){
}

public static void main(String[] args) {
    List<Noticias> noticias = getNoticias();
}

public static List<Noticias> getNoticias(){
    List<Noticias> noticia_list = new ArrayList<Noticias>();
    String sql = "SELECT * from NOTICIAS";

    Connection conexao = null;

    try {
        conexao = DriverManager.getConnection("jdbc:postgresql://localhost:5432/base", "postgres", "postgres");
        System.out.print("Conexao com o banco de dados efetuada com sucesso!");

    } catch (SQLException ex) {
        Logger.getLogger(DB.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println("Erro durante a conexao com o banco de dados!");
    }

    PreparedStatement prepared_sql = null;

    try {
        prepared_sql = conexao.prepareStatement(sql);
    } catch (SQLException e) {
        e.printStackTrace();
    }

    try {
        ResultSet result = prepared_sql.executeQuery();

        while(result.next()){
            Noticias noticia = new Noticias();
            noticia.setGrid(result.getInt("grid"));
            noticia.setTopico(result.getString("topico"));
            noticia.setConteudo(result.getString("conteudo"));
            noticia.setUsuario(result.getInt("usuario"));
            noticia.setData(result.getDate("data"));

            noticia_list.add(noticia);
        }

    } catch (SQLException e) {
        e.printStackTrace();
    }

    return noticia_list;
}
  • Include the log with the exception as well, but it’s probably why you create connection on main, it won’t run if you don’t call it or run it as a java application. I don’t know what your application looks like, but try calling getConexao() in getNoticias()

  • But you have made the postgree jar deploy on your Tomcat?

  • I’ll do what you said @Brunswick to see if it works.

  • @Edgarmunizberlinck did not deploy, I will check this too.

  • @Brunswick put it all in one method called getNoticias(), within this method he tries to make the connection, but without success!

  • Include the stack trace, makes it easier to help.

  • @Brunocésar thanks for trying to help, the problem has been solved... thank you!

Show 2 more comments

1 answer

1


Checks whether the .jar driver is in the directory /WEB-INF/lib.



You’re making pagecontroller?=p=noticias even?

It has 2 equals in this parameter, which totally mocks. Do

pagecontroller?p=noticias


The nullpointer I think it’s because he can’t find the getParameter("p") then you do .equals resulting in the error.


UPDATE

Add Class.forName("org.postgresql.Driver"); before your connection:

try {
    Class.forName("org.postgresql.Driver"); 
    conexao = DriverManager.getConnection("jdbc:postgresql://localhost:5432/base", "postgres", "postgres");
    System.out.print("Conexao com o banco de dados efetuada com sucesso!");

} catch (SQLException ex) {
    Logger.getLogger(DB.class.getName()).log(Level.SEVERE, null, ex);
    System.out.println("Erro durante a conexao com o banco de dados!");
}

  • Already checked and is entering the if, the problem is at the time of fetching the connection...

  • @Luizricardocardoso posts class code News hiding classified information

  • I edited the post, remembering that the connection is returned when I run by Eclipse (Run java application), but in the browser the pointer comes null.

  • @Luizricardocardoso I updated my answer, try and show the log if any

  • I put a Try Class.forName("org.postgresql.Driver"); and fell in catch. The error remains the same, returning a null pointer.

  • @Luizricardocardoso You put the .jar in the /WEB-INF/lib?

  • I changed my Workspace and forgot to put, with the .jar inside the lib folder works... The Class.forName("org.postgresql.Driver") force the correct driver execution?

  • In some previous versions I had to do this to boot, but the main reason is to check if there is a class in your environment

  • Solved your problem?

  • Yes the problem has been solved, thank you!

Show 5 more comments

Browser other questions tagged

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