obtain information from a Java servlet on a web page

I am working on a webpage that displays various coordinates (longitude, latitude), and I need to create a Java class to sort these coordinates.

My plan is to send the coordinates to a Java servlet before displaying them on the webpage. The servlet will then sort them and send them back to the webpage for display.

To achieve this without refreshing the webpage, I believe I need to use Ajax to call the servlet. While I have a basic understanding of how to do this, I'm not sure how to receive data in Java from a webpage.

In the past, I have created servlets that called Java functions using JavaScript. However, one drawback of this approach is that the web browser navigates to a different page (a JSP with Java calls).

While I don't have the specific code for sorting coordinates yet, I am experimenting with the following:

package sorting;

public class SortCoordinates {

    public static String sort(String unsortedString) {
        String sortedString;
        
        // Sorting logic goes here
        sortedString = unsortedString;
        return sortedString;
    }
}

I know how to call a Java function from JavaScript using JSP, but I'm unsure about how to do it from other webpages on different servers or without refreshing the webpage.

Does anyone have any suggestions on how I should proceed? Or could you recommend any resources for further reading?

Answer №1

If you're looking to deepen your understanding beyond the basics, consider diving into these resources:

How do you send an array as part of an (jquery) ajax request

Once you've grasped the concepts from those resources, remember to implement them by using a POST method instead of GET in the following structure:

var valSend = "aSingleParam";

var url = "/yourApplicationWebContext?paramPassed="+valSend;
console.log(url);
$.ajax({
    url: url,
    type: "GET",
    dataType: "json",
    success: function(data) {
    console.log("Data returned : " + data);

        if (typeof data == 'object') {

                }

        },
    error: function(jqXHR, textStatus, errorThrown) {
        console.log("jqXHR : "+jqXHR + " text status : " + textStatus + " error : " + errorThrown);
        }
    });

On the Java Servlet side, ensure that your web.xml includes a servlet and corresponding mapping:

//Your Java Servlet class

package com.xyz;

public class ServlvetClassName extends HttpServlet {

//The type: "GET" in the ajax call will trigger a "get" which the doGet will handle

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

        if(null!= req.getParameter("paramPassed")){
         // get and use your parameter, which "is paramPassed"..... 

        }


        }

//The type: "POST" in the ajax call will trigger a "post" which the doPost will handle

protected void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    this.doGet(req, resp);
}

}

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

Instructions for duplicating the current website address into another browser window or document without user input

I have a desire to create a button within a web browser that, when clicked, will either copy the current URL address into a file or open another web browser and paste it there. Being new to programming, I am unsure of which language to use for this task. ...

AngularJS: intercepting custom 404 errors - handling responses containing URLs

Within my application, I have implemented an interceptor to handle any HTTP response errors. Here is a snippet of how it looks: var response = function(response) { if(response.config.url.indexOf('?page=') > -1) { skipException = true; ...

Tips on accessing a specific block of a file in Rails without having to read it from the start again

I am currently dealing with a continuously growing file (log) that I need to read in specific blocks. To achieve this, I have been using Ajax calls to retrieve a designated number of lines. While attempting to read the necessary lines using File.foreach, ...

Tailored NodeJS compilation incorporating JavaScript modules

Can NodeJS be built together with specific JavaScript modules? I am aware that for native modules, node-gyp can assist with this, but I am unsure about how to accomplish this with JavaScript modules. My goal is to use a custom application without needing t ...

What is the best way to create a Promise that is fulfilled when an event is emitted by an event emitter in JavaScript or Node.js?

Is there a way to create a Promise in Node JS that will only resolve when a specific event is emitted by an event emitter? I am trying out the following code snippet, but I am unsure how to make the promise wait until the event occurs. function bar(resol ...

Learn how to implement a split background effect by simply clicking the SPLIT button

let context = canvas.getContext("2d"); // for canvas size var window_width = window.innerWidth; var window_height = window.innerHeight; canvas.width = window_width; canvas.height = window_height; let hit_counter = 0; // object is created using class clas ...

The statusMessage variable is not defined within the "res" object in a Node Express application

I am currently developing a Node.js & Express.js application and I am in need of creating a route to display the app's status. router.get('/status', function(req, res) { res.send("Current status: " + res.statusCode + " : " + res.stat ...

What is the solution to the error "Maximum update depth exceeded. Calls to setState inside componentWillUpdate or componentDidUpdate" in React?

Everything was running smoothly until this unexpected issue appeared. I attempted to change the condition to componentDidMount, but unfortunately, that didn't resolve the problem. The error is occurring in this particular function. componentDidUpd ...

Merging two arrays to create a JSON object

column_names: [ "School Year Ending", "Total Students", "American Indian/Alaskan Native: Total", "American Indian/Alaskan Native: Male", "American Indian/Alaskan Native: Female", "Asian/Pacific Islander: Total", "Asian/Pacific I ...

Getting rid of the Horizontal Scroll Bar

Having trouble with a persistent horizontal scrollbar in the "section3__container" container despite attempts to adjust size and overflow settings. Need assistance in removing this unwanted feature. <html lang="en"> <head> <m ...

Can you tell me if the "dom model" concept belongs to the realm of HTML or JavaScript?

Is the ability to use "document.X" in JavaScript to visit an HTML page and all its tags defined by the HTML protocol or the ECMAScript protocol? Or is it simply a choice made in the implementation of JavaScript, resulting in slight differences in every bro ...

An error occurred while trying to serialize the `.res` response received from the `getServerSideProps` function in

I encountered the following issue while utilizing the getServerSideProps function to fetch data from Binance API. import binance from "../config/binance-config"; export async function getServerSideProps() { const res = await binance.balance(( ...

Endless cycle within the while loop without any obvious cause

I've been tinkering with a timer and thanks to some feedback I received in this community, everything is running smoothly. Here's what the current version looks like for reference: https://i.stack.imgur.com/Qd7ll.png Here's a snippet of my ...

Using JavaScript to manipulate HTML content that has been dynamically injected using AJAX

I am in the process of developing a portfolio website where I want to fetch partial HTML files using an AJAX request. Here is the basic structure of the HTML: <div id="portfolio"> // Content will be replaced here </div> <a ...

Updating the ContextKey of the DynamicPopulateExtender based on the selected value from a DropDownList dynamically

I am facing an issue with my DynamicPopulateExtender control. I need it to render HTML based on the value of an asp:DropDownList. The problem lies in writing the JavaScript code that can fetch the dropdown value, assign it to the DynamicPopulate control&ap ...

The SMTP request for a one.com domain email is experiencing issues when sent from the render.com server

I have set up an Express JS server on render.com to handle SMTP calls to an email service hosted on one.com with a custom domain. Utilizing nodemailer to manage the SMTP call: app.post("/send-mail", validate(schema), (req, res) => { console. ...

Check for the presence of a horizontal scrollbar on the page for both computer and mobile devices

Is there a way to determine if a web page has a horizontal scrollbar using jQuery or pure JavaScript? I need this information to dynamically change the css of another element. I initially tried function isHorizontalScrollbarEnabled() { return $(docum ...

Issue with loading a link within a tab on jQuery UI Tabs

I'm encountering an issue with jQuery UI tabs. Specifically, I have tabs that are loaded using ajax and my problem is that I want to load page links within the page but am struggling to do so. Below is the code of my page with the tabs: <script&g ...

"Exploring the concept of master pages in web development with the combination

Recently, I have been developing a website that functions similarly to olx, displaying ads based on the visitor's location (for example, showing Mumbai ads if the visitor is from Mumbai). Initially, I was planning to create separate pages for each cit ...

"Encountered a TypeError: Cannot read property 'params

I've encountered an issue with passing the id to my product page. Despite trying various solutions and searching for answers, I still can't get it to work. Below is my index.js code: import React from "react"; import {render} from &quo ...