0
I’m trying to make an entry into a database mysql using Java.
When running the method that creates the database connection, it works. But when making the request by Servlet, when arriving at the method it says that the connection is empty and gives null pointer execption
. If anyone can help me. I’m new to the world of Java.
public class Dao {
Connection con;
PreparedStatement stmt;
PreparedStatement stmtEndereco;
ResultSet rs;
public void open() throws Exception {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/buscaCep", "root", "");
System.out.print("Conexao com o banco Ok");
} catch (Exception ex) {
System.out.println("Conexao falhou");
}
}
public void close() throws Exception {
con.close();
}
public static void main(String[] args) throws Exception {
Dao dao = new Dao();
dao.open();
}
}
When running this file it gives the message "Connected with the ok database".
Servlet
@WebServlet(name = "ClientController", value = "/ClientController")
public class ClientController extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
Integer numeroInt = 0;
ClienteDao clientedao = new ClienteDao();
String name = request.getParameter("nome");
String email = request.getParameter("email");
String cep = request.getParameter("cep");
String logradouro = request.getParameter("logradouro");
String numero = request.getParameter("numero");
String complemento = request.getParameter("complemento");
String bairro = request.getParameter("bairro");
String cidade = request.getParameter("cidade");
String estado = request.getParameter("estado");
numeroInt = Integer.parseInt(numero);
Cliente newCliente = new Cliente(name, email);
Endereco newEndereco = new Endereco(cep, logradouro, numeroInt, complemento, bairro, cidade, estado);
newCliente.setEndereco(newEndereco);
clientedao.insertClient(newCliente);
response.sendRedirect("Sucesso.jsp");
} catch (Exception ex) {
ex.printStackTrace();
} finally {
}
}
}
public class ClienteDao extends Dao{
private static final String INSERT_Cliente_SQL = "insert into usuario" + " (idUsuario, nome, email) VALUES "
+ " (null, ?, ?); ";
public void insertClient(Cliente c) throws Exception {
open();
System.out.println(con);
con.setAutoCommit(false);
int chave = 0;
try {
stmt = con.prepareStatement(INSERT_Cliente_SQL, PreparedStatement.RETURN_GENERATED_KEYS);
stmt.setString(1, c.getNome());
stmt.setString(2, c.getEmail());
stmt.executeUpdate();
rs = stmt.getGeneratedKeys();
rs.next();
chave = rs.getInt(1);
stmt.close();
stmtEndereco = con.prepareStatement("insert into endereco values (null, ?, ?, ?, ?, ?, ?, ?, ?)");
stmtEndereco.setString(1, c.getEndereco().getCep());
stmtEndereco.setString(2, c.getEndereco().getLogradouro());
stmtEndereco.setInt(3, c.getEndereco().getNumero());
stmtEndereco.setString(4, c.getEndereco().getComplemento());
stmtEndereco.setString(5, c.getEndereco().getBairro());
stmtEndereco.setString(6, c.getEndereco().getCidade());
stmtEndereco.setString(7, c.getEndereco().getEstado());
stmtEndereco.setInt(8, chave);
stmtEndereco.executeUpdate();
stmtEndereco.close();
con.setAutoCommit(true);
con.commit();
con.close();
} catch (Exception ex) {
con.rollback();
throw new Exception(ex.getMessage());
} finally {
System.out.println("Cheguei aqui");
}
}
}
However, when sending the data through the archive Servlet, he always accuses this mistake:
Conexao falhou
null
java.lang.NullPointerException
at br.com.stefanini.buscacep.persistence.ClienteDao.insertClient(ClienteDao.java:13)
at br.com.stefanini.buscacep.controller.ClientController.doPost(ClientController.java:44)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:681)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:232)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:167)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:194)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:167)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:544)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:698)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:364)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:624)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:831)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1651)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:834)
If anyone knows how to fix it, I really appreciate it.
Welcome @Matheus Alencar, include a
System.out.println(ex.getMessage());
belowSystem.out.println("Conexao falhou");
in classDao
and inform which error message was displayed.– Clarck Maciel