How to pass a Java String to Javascript

3

It is a java web application project. I want to put a bookmark using google maps, I have my jsp where I show it and I have the javascript where I use the api. I have a java where I make the connection to the bd MySQL and another where I make the query to bring the data. Up here everything is fine.

Now, the coordinates where I want to put the marker are in the bd.

My question is, how do I pass the coordinates that I already brought them from the bd and I have them in the java, to the javascript to use them with the api.

PD. I've seen and read something about what servlet can be used for and that, but I do not quite understand.

public class Conexion {

private static Connection cnx = null;

public static Connection obtener() throws SQLException, ClassNotFoundException {
   if (cnx == null) {
      try {
         Class.forName("com.mysql.jdbc.Driver");
         cnx = DriverManager.getConnection("jdbc:mysql://localhost/deliveryTrackingBD", "root", "root");
      } catch (SQLException ex) {
         throw new SQLException(ex);
      } catch (ClassNotFoundException ex) {
         throw new ClassCastException(ex.getMessage());
      }
   }
   return cnx;
}

public class Query {

private final String tabla = "Pedido";

public Pedido recuperarPorId(Connection conexion, int id) throws SQLException {
   Pedido pedido = null;
   try{
      PreparedStatement consulta = conexion.prepareStatement("SELECT Direccion FROM " + this.tabla + " WHERE Id = ?" );
      consulta.setInt(1, id);
      ResultSet resultado = consulta.executeQuery();
      while(resultado.next()){
         pedido = new Pedido(id, resultado.getString("Direccion"));
      }
   }catch(SQLException ex){
      throw new SQLException(ex);
   }
   return pedido;
}

Then I have an index.jsp where I only have the <div id="map"></div> to use the Google map api and the reference to the javascript file. In this I only have what is necessary for the api.

    
asked by Juan Manuel 27.10.2016 в 02:12
source

1 answer

2

If you have all your direct Java code in the JSP in the form of scriptlet, then what you can do is print the content of your variable String directly into the JavaScript code. Here is an example:

<html>
<!-- código HTML, CSS, etc -->
<%
    //esto es Java
    String coordenadas = ...; //inicializas coordenadas de alguna manera
%>

<script type="text/javascript">
    //esto es JavaScript
    function muestraCoordenadas() {
        var coordenadas = "<%= coordenadas %>";
    }
</script>

Where <%= coordenadas %> will be interpreted by your JSP and replaced by the value of the variable coordenadas of your scriptlet in Java.

    
answered by 28.10.2016 в 06:46