I can not insert values into the database with Java Servlet

0

I have a database and I want you to insert values in the table ... the program does not throw any errors ... but it simply does not insert the values in the database ... When I make an insertion through the database is fine ... but I can through the servlet ...

What is the problem? I have put the JDBC library. I'm using the GlasshFish server.

 package hotelreserva;


 import java.util.*;  
 import java.sql.*; 
 import java.io.IOException;
 import java.io.PrintWriter;
 import java.sql.Connection;
 import java.sql.DriverManager;
 import java.sql.PreparedStatement;
 import javax.servlet.http.HttpServletResponse;










      public class cliente {




      private static Connection getConnection() {
      //To change body of generated methods, choose Tools | 
      Templates.
     try {


     Class.forName("com.mysql.jdbc.Driver").newInstance();
     Connection con= cliente.getConnection(); 
     DriverManager.getConnection(
            "jdbc:mysql://localhost:3306/hotelres", "root", "root");
     PreparedStatement ps=con.prepareStatement("insert into 
     T_reserva (localizador) values (?)");  


    cliente c;
    c = new cliente();
    ps.setString(1,"sdsdsd");  

    ps.executeUpdate();



   } catch (Exception ex) {
      ex.printStackTrace();

  }
  return null;
    
asked by TOMAS 15.11.2017 в 18:41
source

1 answer

0

Well there are a couple of things that catch my eye, first the mysql table that starts with a capital letter, usually start with lowercase, then you talk servlet but I do not see either doGet () or doPost (). I do not know your level of programming related to servlets but I'll give you a complete example of how you should do what you were trying to do. First create a dynamic web project, second that the system creates you within the folder WebContent / WEB-INF / web.xml is exclusive for the classic servlets to work.

Now I'm going to give you a list of steps to take into account:

Connection file:

package com.soa.dao;

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

public class ConnectionStackOverflow {

private final static String user = "root";
private final static String password = "root";

public static Connection getConexion() throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException {
    Class.forName("com.mysql.jdbc.Driver");
    Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/hotelres" , user, password);
    return connection;
}

public static void closeConnection() throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException {
    getConexion().close();
}
}

DB Insertion Driver File

package com.soa.controllers;

import java.sql.Connection;
import java.sql.PreparedStatement;
import com.soa.dao.ConnectionStackOverflow;

public class ClientController {

public static void insertClient(String localizador) {
    Connection connection = null;

    try {
        connection = ConnectionStackOverflow.getConexion();

        if (connection != null) {
            PreparedStatement ps;
            String sql = "INSERT INTO T_reserva(localizador) VALUES(?)";
            ps = connection.prepareStatement(sql);
            ps.setString(1, localizador);
            ps.executeUpdate();
            ps.close();
            System.out.println("Query executed");
        } else {
            System.out.println("Connection appears to be null");
        }
    } catch (Exception error) {
        System.out.println("Cannot even connect");
        error.getMessage();
        error.printStackTrace();
    }
}

}

Servlet file that should be connected or declared in the web.xml pay attention

package com.soa.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.soa.controllers.ClientController;

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

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

    try {

        String localizador = request.getParameter("localizador");
        ClientController.insertClient(localizador);

    } catch (Exception error) {
        error.getMessage();
        error.printStackTrace();
    }

    response.getWriter().append("Los datos fueron insertados");
}
}

JSP file (Inside WebContent, in this case we put index.jsp) with a FORM from where you are going to send the data that will reach the Servlet and the servlet will enter the method of the class ClientController

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<!-- el envío de datos lo estamos haciendo por javascript capturando los datos del form y enviándolo directamente al servlet -->
<script type="text/javascript">

function send(){
    var frm = document.frmLocalizador;
    frm.submit();
}

</script>

<body>
    <h1>Localizador</h1>

    <form action="LocalizadorServlet" method="get" name="frmLocalizador">
        <input type="text" name="localizador" />
        <input type="button" value="boton" onclick="send()" />
    </form>
</body>
</html>

File web.xml configuration with respect to the route of the packages together with the servlet

    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://java.sun.com/xml/ns/javaee"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
        id="WebApp_ID" version="3.0">
        <display-name>StackOverflowWeb</display-name>
        <welcome-file-list>
            <welcome-file>index.html</welcome-file>
            <welcome-file>index.htm</welcome-file>
            <welcome-file>index.jsp</welcome-file>
            <welcome-file>default.html</welcome-file>
            <welcome-file>default.htm</welcome-file>
            <welcome-file>default.jsp</welcome-file>
        </welcome-file-list>

        <servlet>
            <servlet-name>LocalizadorServlet</servlet-name>
            <servlet-class>com.soa.servlets.LocalizadorServlet</servlet-class>
        </servlet>

        <servlet-mapping>
            <servlet-name>LocalizadorServlet</servlet-name>
            <url-pattern>/LocalizadorServlet</url-pattern>

        </servlet-mapping>
    </web-app>

Image of how the project structure should look.

I do not want to seem superb, but if you do not go with these files later it is because there is some conflict regarding the path, user and / or password of the connection, as it may also be that the insert query is not well done , because you did not determine the type of data that the table receives nor the total number of columns that the table has. Another issue to keep in mind is that the connector downloads it from here and copies it to the folder WEB-INF / lib , once there you touch right button on the file - > Build Path - > add to Build Path .

The connector downloads it from here:

link You have to download the one that says JAR.

Another connector can also walk but that never failed me.

I tried it with a table that I created with that column name and it works very well, however I left the original query in the code I did.

I made you a mini servlet project in an hour, many very large companies are still working with this system but with endless amounts of servlets unbeatable, Well if you served marcala as solved.

Once you have added the connector to the build path, you will be able to use the internal packages that connector has in your project, but do not worry that you do not have to do anything with it.

If you put the connector, and you are sure that the key and password along with the address is well configured in the connection file and however it is not the same, you can try changing this line like this:

DriverManager.getConnection ("jdbc: mysql: // localhost / hotelres", user, password);

Excluding the port number on the route may be fun.

If something of what I spent is useful for you, fix yourself a vow or something that took me a long time to answer and I know it works well.

Axel.

    
answered by 16.11.2017 / 05:15
source