Sending JSON data from a JSP page to a JavaScript file

I have a JSON string (using Gson) containing data from my database in a JSP file, and I want to pass this information to a JavaScript function.

JSP (consulta.jsp):

<%@ page language="java" import="java.sql.*" %>
<%@ page language="java" import="db.Conexao" %>
<%@ page language="java" import="java.util.ArrayList" %>
<%@ page language="java" import="com.google.gson.Gson" %>

<%
try {
// create connection instance
Conexao conexao = new Conexao("localhost", "app", "root", "diogo");
// connect to the database
Connection connection = conexao.connect();

// create statement and execute query
Statement st = connection.createStatement();
String sql = "SELECT * FROM crimes";
ResultSet rs = st.executeQuery(sql);

final ArrayList<String> id= new ArrayList<String>();

while(rs.next()) {
    id.add("id");
    id.add(rs.getString("id"));
    id.add("latitude");
    id.add(rs.getString("latitude"));
    id.add("longitude");
    id.add(rs.getString("longitude"));
}

String[] array = new String[id.size()];
array = id.toArray(array);

Gson gson = new Gson();
String json = gson.toJson(array);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);

// close the database connection
connection.close();
}
catch(Exception e) {
out.println(e.toString());
}

%>

JS function:

function loadPoints() {

$.getJSON('consulta.jsp', function(points) {

    $.each(points, function(index, point) {

        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(LATITUDE VALUE HERE, LONGITUDE VALUE HERE),
            title: value,
            map: map,
            icon: 'arma2.png'
        });
    }
}

PS:. The JSON string is ["id","1","latitude","-23.4831104000","longitude","-46.6330227000","id","4","latitude","-23.5874328731","longitude","-46.6573598700"]. Is it correct? Thank you.

Answer №1

To enhance the efficiency of your data structure, consider creating a list of maps:

final ArrayList<HashMap<String, String>> id= new ArrayList<HashMap<String, String>>();

while(rs.next()) {
    HashMap<String, String> map = new HashMap<String, String>();
    map.put("id", rs.getString("id"));
    map.put("latitude", rs.getString("latitude"));
    map.put("longitude", rs.getString("longitude"));
    id.add(map);
}

You may not need to convert the ArrayList to an array before using Gson to generate JSON directly:

Gson gson = new Gson();
String json = gson.toJson(id);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);

The resulting JSON will resemble:

[{"id": "1", "latitude": "-23.483", "longitude": "46.633"}, ... ]

This will simplify your JavaScript code when integrating with Google Maps:

$.getJSON('consulta.jsp', function(pontos) {

    $.each(pontos, function(index, ponto) {

        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(ponto.latitude, ponto.longitude),
            title: value,
            map: map,
            icon: 'arma2.png'
        });
    }
});

Keep in mind that the Google Maps API may require numerical lat/long values rather than strings:

$.getJSON('consulta.jsp', function(pontos) {

    $.each(pontos, function(index, ponto) {

        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(+ponto.latitude, +ponto.longitude),
            title: value,
            map: map,
            icon: 'arma2.png'
        });
    }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to deselect a checkbox using AngularJS

I have a checklist of items <input type="checkbox" ng-model="servicesModel" value={{item.name}} id={{item.name}} ng-click="toggleSelection(item.name)"/> and I need to unselect the currently selected checkbox $scope.toggleSelection = function toggl ...

What is the best way to conceal a callback form once it has been successfully submitted?

In my callback form, everything seems to be functioning properly. However, there is a slight issue when the client hits the submit button multiple times. Each time they do so, a notification saying "Your request sent successfully" pops up next to the butto ...

Switch the orientation of a live table moving horizontally to vertically and vice versa

config.previewData = [ { Products:27989, Total Customers:294, Metrics:"MVC", Toner Products:5928, INK Products:22061 }, { Products:56511, Total Customers:376, Metrics:"SMB", ...

Tips for retrieving multiple independent response data in Express js app.get callback

What is the optimal way to send two independent MongoDB results in an Express application via HTTP Method? Check out this concise example to clarify: //app.js var express = require('express'); var app = express(); var testController = require(& ...

Calling a function within another function is not allowed in Typescript

Essentially, I have an Angular Web Page that uploads a file to the server via a POST request, which is then received by my NodeJS app. The issue arises when attempting to retrieve the file path in subirArchivo() and pass it to a function called InsertaPer ...

Regular expression for ensuring the validity of a currency amount with a specific minimum value

Currently, I have a regular expression that successfully validates money. ^\d{1,3}(,\d{3})*$ However, I now need to modify it to include a minimum amount requirement of 20,000. Can someone assist me with this adjustment? Fiddle: fiddle updated ...

Customize the appearance of disabled dates in the eonasdan-datetimepicker styling

I am seeking to customize the default styles for the "eonasdan-datetimepicker" (https://github.com/Eonasdan/bootstrap-datetimepicker) by implementing a basic hover message feature. The CSS attributes currently applied to disabled dates are as follows: .bo ...

Utilizing Bootstrap and customized JavaScript functions for enhancing form validation

I am in the process of creating a form that includes multiple validation rules for most of its fields. Initially, I utilized Bootstrap form validation because I appreciate its handling of error messages and valid input notifications to the user. This metho ...

Issue with the display of Google reCaptcha verification popup within Mat Dialog

While working on an angular material dialog form, I integrated Google reCaptcha. However, when the reCaptcha verification popup appears, it displays above the form as shown in the image. https://i.sstatic.net/ax8QN.jpg I noticed that every time the mat d ...

What is the best way to showcase 3 items on each slide while retrieving the data from the database instead of using static html?

While reviewing the documentation for this slider plugin, I encountered a problem. http://www.slidesjs.com/#docs I couldn't find instructions on how to display 3 items on a single slide. For example, if I have a $data object and use a PHP foreach lo ...

Reloading the page using ajax technology

What is the best way to handle logging out on a webpage without reloading the page? Thanks in advance!) My perspective: def logout(request): auth.logout(request) html = render(request, 'base.html') return html Using Ajax: $('a[hre ...

"Revolutionize real-time data updates with Node.js, Redis, and Socket

Greetings! I am currently working on a project for my school that involves creating a "Twitter clone." My goal is to incorporate a publish subscribe pattern in order to facilitate real-time updates. One key feature users will have access to is the abili ...

What is the best way to transfer a file to a server using a node library, like axios for instance

When using the CURL command to upload a file to a server, I have encountered an issue with a few CLIs. It seems that only CLIs with CURL installed are working fine when running my node app. let filesPath = `http://abc/api/789012/files-api`; exec(`curl - ...

I constructed a table using a loop, and now I am interested in setting up a click event for each individual cell

for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { string empCode = ds.Tables[0].Rows[i]["EMP_CODE"].ToString(); string empName = ds.Tables[0].Rows[i]["EMP_NAME"].ToString(); string gradeCode = ds.Tables[0].Rows[i]["GRADE_CO ...

angucomplete-alto automatically fills in data based on another input

Having two autocomplete select boxes with a unique feature has been quite interesting. The first input accepts a code that is related to a label, autofilling the second input with the corresponding object once the code is selected in the first input. Howev ...

What is the method to retrieve the ID name of an HTML tag based on its value?

Is there a way to determine the ID of an HTML tag based on its content? For example, if I have the following textboxes: I need to identify the id with the value "A2" So the expected result is id=option2 because its value is A2 <input type="text ...

What is the method for tallying CSS page breaks in printed HTML documents?

Currently, for my report generation process using HTML and CSS to manage page breaks dynamically. I've enabled the option for users to print multiple reports at once by combining them into different sections within a single HTML document. This helps p ...

The concept of undefined in JavaScript when an if condition is applied

In Node.js, there is a method used to handle API requests. An unusual behavior occurs when dealing with req.query.foo - even if it has a value defined, it becomes undefined when used in an if condition as shown below. Additionally, another req.query.foo ...

What is the process of transforming an Angular object that includes nested child objects and arrays?

I'm currently working on an Angular project and I am looking for a way to extract and modify the formData before sending it to the server as JSON. Here is the original data: { "BioData":{ "firstname": "Greg", " ...

Upon sending a POST request, an UnhandledPromiseRejectionWarning was triggered due to an unhandled promise

Whenever I try to make a post request, I keep encountering this particular error message: UnhandledPromiseRejectionWarning: Unhandled promise rejection. If anyone out there can shed some light on why this issue is occurring, I would be extremely grateful ...