Tomcat: The server encountered an Internal error that prevented it from fulfilling this request

Asked

Viewed 372 times

0

I’m having problems with Tomcat using Eclipse. First he couldn’t find the Mysql Driver, then I used Class.forName in class ConnectionFactory and now he’s returning to line 52 AdicionaContatoServlet as null.

Can anyone help me? Here it is :

Connectionfactory.java.

package br.com.caelum.servlet;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionFactory{
    public Connection getConnection () throws ClassNotFoundException{
        try{
            Class.forName("com.mysql.jdbc.Driver");
            return DriverManager.getConnection(
                    "jdbc:mysql://localhost/agenda", "gabriel","******");
        } catch(SQLException e){
            throw new RuntimeException(e);
        }
    }
}
//"jdbc:mysql://localhost/agenda", "gabriel","***********");

Java contact.

package br.com.caelum.servlet;

import java.util.Calendar;

public class Contato {
    private Long id;
    private String nome;
    private String email;
    private String endereco;
    private Calendar dataNascimento;

    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getNome() {
        return nome;
    }
    public void setNome(String nome) {
        this.nome = nome;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getEndereco() {
        return endereco;
    }
    public void setEndereco(String endereco) {
        this.endereco = endereco;
    }
    public Calendar getDataNascimento() {
        return dataNascimento;
    }
    public void setDataNascimento(Calendar dataNascimento) {
        this.dataNascimento = dataNascimento;
    }
}

Contactodao.java

package br.com.caelum.servlet;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import br.com.caelum.servlet.ConnectionFactory;
import br.com.caelum.servlet.Contato;

public class ContatoDao {

    private Connection connection;

    public ContatoDao() throws ClassNotFoundException{
        this.connection = new ConnectionFactory().getConnection();
    }

    public void adiciona(Contato contato){
        String sql = "insert into contatos" +
                "(nome, email, endereco, dataNascimento)"+
                "values (?,?,?,?)";

        try{
            PreparedStatement stmt = connection.prepareStatement(sql);

            stmt.setString(1,contato.getNome());
            stmt.setString(2,contato.getEmail());
            stmt.setString(3,contato.getEndereco());
            stmt.setDate(4, new Date(
                    contato.getDataNascimento().getTimeInMillis()));

            stmt.execute();
            stmt.close();
        } catch(SQLException e){
            throw new RuntimeException(e);
        }
    }

    public void altera(Contato contato){
        String sql = "update contatos set nome=?, email=?,"+
                "endereco=?, dataNascimento=? where id=?";

        try{
            PreparedStatement stmt = connection.prepareStatement(sql);
            stmt.setString(1, contato.getNome());
            stmt.setString(2, contato.getEmail());
            stmt.setString(3, contato.getEndereco());
            stmt.setDate(4, new Date(contato.getDataNascimento().
                    getTimeInMillis()));
            stmt.setLong(5, contato.getId());
            stmt.execute();
            stmt.close();
        } catch(SQLException e){
            throw new RuntimeException(e);
        }
    }
    public void remove(Contato contato){
        String sql = "delete from contatos where id=?";

        try{
            PreparedStatement stmt = connection.prepareStatement(sql);

            stmt.setLong(1, contato.getId());
            stmt.execute();
            stmt.close();
        }catch(SQLException e){
            throw new RuntimeException(e);
        }
    }

    public List <Contato> getLista(){
        try{
            List<Contato> contatos = new ArrayList<Contato>();
            PreparedStatement stmt = this.connection.
                    prepareStatement("select * from contatos");
            ResultSet rs = stmt.executeQuery();

            while(rs.next()){
                Contato contato = new Contato();
                contato.setId(rs.getLong("id"));
                contato.setNome(rs.getString("nome"));
                contato.setEmail(rs.getString("email"));
                contato.setEndereco(rs.getString("endereco"));

                Calendar data = Calendar.getInstance();
                data.setTime(rs.getDate("dataNascimento"));
                contato.setDataNascimento(data);

                contatos.add(contato);
            }
            rs.close();
            stmt.close();
            return contatos;
        } catch(SQLException e){
            throw new RuntimeException(e);
        }
    }
}

Adds contactoservlet.java

package br.com.caelum.servlet;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.ParseException;

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

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

        PrintWriter out = response.getWriter();

        String nome = request.getParameter("nome");
        String email = request.getParameter("email");
        String endereco = request.getParameter("endereco");
        String dataEmTexto = request.getParameter("dataNascimento");
        Calendar dataNascimento = null;

        try {
            Date date = new SimpleDateFormat("dd/MM/yyyy").parse(dataEmTexto);
            dataNascimento = Calendar.getInstance();
            dataNascimento.setTime(date);
        } catch (ParseException e){
            out.println("Erro de conversão de data");
            return;
        }

        Contato contato = new Contato();
        contato.setNome(nome);
        contato.setEmail(email);
        contato.setEndereco(endereco);
        contato.setDataNascimento(dataNascimento);

        ContatoDao dao = null;
        try{
            dao = new ContatoDao();
        }catch(ClassNotFoundException e){
            e.printStackTrace();
        }
        dao.adiciona(contato); //linha 52

        out.println("<html>");
        out.println("<body>");
        out.println("Contato" + contato.getNome() + "adicionado com sucesso!");
        out.println("</body>");
        out.println("</html>");
    }
}

and the error of Tomcat8:

java.lang.NullPointerException
br.com.caelum.servlet.AdicionaContatoServlet.service(AdicionaContatoServlet.java:52)
javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
  • Which line 52?

  • @Gustavocinque gives Ctrl+f //linha 52

  • dao.adiciona(contato); should be inside the try/catch. Probably the dao is falling in catch and is not being initialized correctly.

  • Understood. And if I also put after the catch a finallu{dao.add(contact)}, would that be a good ? Could it work ? I can only test the night...

  • It seems to me there’s no reference in the dao, @Gabriel, you’d have to fix it. With a Finally do not believe it would work, would release the same error on the console, it can not find the dao reference. For testing, start by trying to instantiate dao outside the block try, so you can see the error launched.

  • I’m realizing something... It seems to me that the problem is in connection. You see, I had not attempted to commit myself to this before but, when you instancia a dao, if it gives error it throws a ClassNotFoundException. The only place a mistake like that could happen is in Class.forName("com.mysql.jdbc.Driver");. You have the class in the project dependencies?

  • I have connectionfactory with Class.forName within it in the same package as the whole project. both are in extension . java...

  • But vc has the Mysql dependency on the project’s Build Path?

  • For it to work, if that’s what’s missing, just download the connector by here, right click on your Eclipse project, choose Build Path, Configure Build Path, Libraries, Add Jars. As I recall this is it.

  • At the beginning of the project I copied the mysql driver to the folder and clicked on build path -> add to build path. It would be the same thing ?

  • No longer know @Gabriel. Take a look at the following, I don’t know what else to tell you, but the default of mysql is localhost:3306, try to see if this is it.

  • Thanks, as soon as I get home I’ll take a look !

Show 7 more comments
No answers

Browser other questions tagged

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