Execute an asynchronous request using Javascript to communicate with a Spring Controller

I've created a JSP page that includes some JavaScript code:

function sendData(tableID) {


    var table = document.getElementById(tableID);


    var dataArray= new Array();

    for (var i = 1;i<table.rows.length; i++){

        var row = table.rows[i];
      
        for (var j = 0; j < row.cells.length; j++){

            alert("Added to array: "+row.cells[j].getElementsByTagName('INPUT')[0].value);
            
            dataArray.push(row.cells[j].getElementsByTagName('INPUT')[0].value);

        }
    }
    
    var ajaxRequest;  

    try{
        
        // Creating XMLHttpRequest object
        ajaxRequest = new XMLHttpRequest();
        
    } catch (e){
       
        // Handling older versions of Internet Explorer 
        try{
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
            
        } catch (e) {
           
            try{
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                
            } catch (e){
                
                alert("Your browser doesn't support AJAX!");
                return false;
            }
        }
    }

    // Sending POST request to 'proyecto/saveRecompensas' URL
    
    ajaxRequest.open('POST', 'proyecto/saveRecompensas');

    ajaxRequest.send('dataArray='+dataArray);

}

I also have a Controller with a method designed to handle the request along with the array data sent from the JavaScript function:

@RequestMapping ("/proyecto/saveRecompensas")
public String saveData(@RequestParam String[] dataArray){
     System.out.println("saveData method");

     return null;        
}

The problem lies in the fact that the sysout statement within the method is not being executed. Consequently, when the JavaScript function runs, the server console displays the following warning message:

WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/myapp/proyecto/proyecto/saveRecompensas] in DispatcherServlet with name 'appServlet'

It appears there is an issue with the URI having double "proyecto". How should I structure the URL for the server to properly receive the request? Am I correctly sending the parameters?

Thank you.

EDIT:

Here's my Dispatcher configuration:

<servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

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

Answer №1

To ensure proper functionality, it's important to specify either a suffix or a sub path instead of just the root path.

  • Sub path approach:

Servlet mapping:

<servlet-mapping>
    <servlet-name>appServlet</servlet-name>
    <url-pattern>/action/*</url-pattern>
</servlet-mapping>

Action method:

@RequestMapping("/proyecto/saveRecompensas")
public String saveRecompensas(@RequestParam String[] array){
    System.out.println("saveRecompensas method");
    return null;        
}

URL path:

ajaxRequest.open('POST', 'action/proyecto/saveRecompensas');
  • Suffix approach:

Servlet mapping:

<servlet-mapping>
    <servlet-name>appServlet</servlet-name>
    <url-pattern>*.action</url-pattern>
</servlet-mapping>

Action method:

@RequestMapping("/proyecto/saveRecompensas")
public String saveRecompensas(@RequestParam String[] array){
    System.out.println("saveRecompensas method");
    return null;        
}

URL path:

ajaxRequest.open('POST', 'proyecto/saveRecompensas.action');

@Edit get an array param in controller method:

  • In Java:

    • When using @RequestParam, make sure to use 'value="paramName[]"' to specify parameter names, which must end with "[]"
    • Parameters should be defined as array types,

    For example:

    public Map<String, Object> getObjects(@RequestParam(required = true, value = "ids[]") Integer[] ids) {
    }

  • In JavaScript:

    • The name of the array parameter should also include the suffix "[]",

    For instance: "ids[]":[1,2,3]

Answer №2

I believe the current URL context is: /myapp/proyecto so when you use:

ajaxRequest.open('POST', 'proyecto/saveRecompensas');

The system will consider the current URL context and add proyecto to it once more.

Answer №3

To make your URLs more user-friendly, you can simply add a suffix in the web.xml file like this:

<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

Then, you can call the controller method from AJAX using the code below:

 $.ajax({
        url:"your_url.do",
        type: "POST",
        data: {'somename':data},
        success: function(data)
        {
            console.log(data);
        }
    });

This approach should work smoothly for you.

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

"The sliding function of the React Bootstrap carousel is malfunctioning as it goes blank just before transitioning

Here is the code snippet I am working with: Whenever the carousel transitions to the next image, the current image disappears before displaying the next one. I am using react-bootstrap version 5.1.0, but it seems like there may be an issue with the transi ...

Best practices for updating nested properties in Angular objects

I have a dataset that includes information about fruit prices for different years: { "fruits": [ { "name": "apple", "prices": [ { "2015": 2, "2014": 3, ...

Combining platform-express and platform-fastify for optimal performance

I am currently working on a NestJS application and my goal is to upload files using the package @types/multer. However, I encountered an issue while following the guidelines from the official documentation: https://i.sstatic.net/JCX1B.png Upon starting ...

The JavaScript .load() function fails to run

Attempting to create a straightforward Newsfeed page based on user interests. Here is the code I have implemented for this purpose. The issue I'm facing is that while the code works fine on my local server, it encounters problems when running on an on ...

Selenium htmlUnit with dynamic content failing to render properly

My current project involves creating Selenium tests for a particular website. Essentially, when a user navigates to the site, a CMS injects some dynamic elements (HTML + JS) onto the page. Everything works fine when running tests on the Firefox driver. H ...

How to retrieve the image source using jQuery

<img src="../img/arnold.png" alt="Arnold"> Is there a way to retrieve the absolute path of this image using jQuery? Currently, when I use img.attr("src"), it only returns "../img/arnold.png", but I need it to return something like "http://site.com/ ...

Menu options

I am currently working on developing a mouseover navigation website. Initially, my design included main buttons for "Our Team", Locations, and Patient Resources. Here is the basic structure I had before attempting to switch to a mouseover approach... &l ...

Exploring the differences between detecting the XMLHttpRequest object in JavaScript and using the try

When it comes to determining browser support for AJAX, I typically rely on object detection like this: if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else if (window.ActiveXObject) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } ...

Jesting around with mocking console.error leads to test failures

The Issue: Currently, I am working on testing React components using Jest and Enzyme. In order to check for properties in development, I have incorporated the prop-types module. The prop-types module relies on console.error to alert when mandatory props a ...

How do I find the child elements within a parent node?

I am currently utilizing a jquery plugin that has rendered the following HTML layout in the browser: <html> <body> <div class="mce-container-body"> ... <input type="text" id="textedit01"> ... </di ...

Ways to access a global JavaScript object in a separate .js file

How can I access an object that was initialized in my HTML document? This is what my HTML document looks like: ... <script type="text/javascript" id="controller">var controller = false;</script> ... <body onload="controller = ne ...

Looking for a JavaScript regex pattern that matches strings starting with the letter "p" and containing at least

I have recently started learning about JavaScript regular expressions. I attempted the following expression for a string starting with the letter "p" followed by digits: p1749350502 The letter "p" is constant and the remaining digits are variable. Howeve ...

Creating a website with multiple custom loops in one page using Wordpress and implementing pagination

The resource provided at http://codex.wordpress.org/The_Loop#Multiple_Loops offers a helpful explanation, but it falls short in guiding me on how to incorporate pagination for multiple loops. I have come across similar inquiries on this topic within the co ...

Incorrect behavior of responsive background images

For the first time, I am working on a school project that requires me to create a responsive website. I am following the "mobile first" approach. On stackoverflow, I came across a helpful way of making background images responsive: background-image: url(. ...

When the FileReader reads the file as readAsArrayBuffer, it ensures that the correct encoding is used

Currently, I am developing a script in JavaScript to read uploaded .csv/.xlsx files and convert the data into an array containing each row. Using FileReader along with SheetJs, I have successfully managed to achieve this by implementing the following code: ...

Repetitive display of MYSQL data occurring

I am currently working on a project where I need to fetch data from a MySQL table and display it using AJAX. While I have been able to successfully show the records, I am facing an issue where the records seem to be displayed in a loop. For example, if I h ...

Select an image based on the input value provided

I'm new to coding and I'm attempting to replicate the search functionality of icomoon where typing a word displays related images. However, I'm facing an issue where I can't seem to get the value entered in the input field to trigger an ...

"Encountering a 401 Error with Rails Devise while using a

I've encountered a challenge while trying to send a basic $.ajax request to a Rails application running locally. When I initiate the request from the console, everything functions as expected. However, when I trigger the call from a Safari extension, ...

Trigger the click event on a specific class selector to extract the corresponding ID

I have an HTML Table with each row: <table> <tr><td><a href='#' id='1' class='delete'>delete</a></td></tr> <tr><td><a href='#' id='2' class='de ...

How can I retrieve the value of a specific <span> element by referencing the class of another <span> within

I have come across the following HTML: <div class="calculator-section"> <p> <span class="x"></span> <span class="amount">30</span> </p> <p> <span class="y"></span ...