Transfer a JSON object to a Java Class without relying on a servlet

I have a form in HTML where I collect user input and store it as an object in JavaScript. Here is how I am creating the object:

var dataObject = {
            Name: getName(),
            Age : getAge()
}

Now, I want to send this object using Ajax to a backend Java Class (not a servlet). Here's my attempt:

    $.ajax({
    url: 'ServerResource',
    type: 'POST',                                                      
    dataType :'json',
    data: dataObject,
    success: function(response) {
        alert('Data sent successfully!');
    },
    error: function(){
        alert('Error occurred while sending data');
}});

However, when I try to run this code, I encounter a 404 Error stating 'Resource not found'. Any insights on why this issue might be arising? My goal is to pass data from client-side JavaScript to server-side Java for further processing. Also, please note that I am testing this on Internet Explorer (IE).

Additional Info: Here is a snippet of my ServerResource.java:

    public class ServerResource extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public ServerResource(String dataObject) {
        // TODO Auto-generated constructor stub
        System.out.println(dataObject);
        System.out.println("Inside Server Resource!");
    }
}

web.XML:

    <?xml version="1.0" encoding="ISO-8859-1"?>
<!--
 Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" basis,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<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" metadata-complete="true" version="3.0">
  <display-name>Welcome to Tomcat</display-name>
  <description>
     Welcome to Tomcat
  </description>
</web-app>

Answer №1

When you encounter a 404 error, it means that the server is unable to find the requested resource at the specified URL. In your case, you mention that you do not want to utilize a Servlet but are attempting to make a POST request to one.

The correct URL format should resemble something similar to /logHandler/. Within the Java web framework you are currently using, you would need to map the servlet (or another type of handler) to that specific URL. It's important to note that you cannot directly reference a class from the client side.

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

In what way is the reference to "this" passed in the function that follows?

I came across the following example in the JS manual, which is functioning correctly: let worker = { someMethod() { return 1; }, slow(x) { alert("Called with " + x); return x * this.someMethod(); // (*) } }; function cachingDecorator ...

Tips for executing a .exe file in stealth mode using JavaScript?

I am currently working on the transition of my vb.net application to JavaScript and I am facing a challenge. I need to find a way to execute an .exe file in hidden mode using JS. Below is the snippet from my vb.net code: Dim p As Process = New Pro ...

Switch between adding elements to various div containers

Can we implement a functionality where clicking an anchor tag moves the .item from .region1 to .region2, and then moving it back to .region1 when clicked again? Essentially creating a toggle behavior? <a href="#" class="btn">Click</div> &l ...

Incorporate a dropdown menu based on the selection made in another dropdown menu

I have a scenario on my website where I want to dynamically add select boxes based on the value selected in the previous one. Here is the code snippet: <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.js"> </script> & ...

The failure of the ajax call to encapsulate is likely due to issues with object visibility

Having some trouble with a piece of code meant to run smoothly on Firefox 3.6. The issue arises when the variable this.xmlhttp, defined in STEP2 and used in STEP3, seems to be operating in different variable environments. Even though I expect the two usa ...

Next.js application deployment halted due to an unsuccessful completion of the process with the command "/bin/bash -ol pipefail -c npm ci"

After completing the development of a Next.js application (discord clone), I encountered an issue while trying to deploy it on Railway. The error message was: Dockerfile:20 ------------------- 18 | ENV NIXPACKS_PATH /app/node_modules/.bin:$NIXPACKS_P ...

Instructions on removing the initial item from a JSON document

I'm currently working on a Node.js project where I need to implement a queue functionality. Specifically, my goal is to delete the first JSON object in my JSON file. The process involves creating and storing users in a JSON file, then adding them to ...

Developing a react native library (create-react-native-library) incorporating a distinct react-native version within its designated Example directory

I'm looking to develop a React Native library, but the testing folder (example folder) it contains the latest version of React Native. However, I specifically need version 0.72.6 in the example folder. Is there a command for this? Current command: np ...

Display HTML components as JSON data using AngularJS

Recently, I started exploring angular js and faced a challenge in formatting json data with the help of angular js. Below is a snippet of my json data: [ {"field_add_link": "<a href=\"/drupal3/drupal3/\">Home</a>"}, {"field ...

Error occurred in main thread due to missing class definition: java.lang.NoClassDefFoundError for io/restassured/response/Response

Creating a POJO class for logging in to Jira localhost. package com.rest.requestpojo; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class LoginApi { @SerializedName("username") @Expose private St ...

What is the best way to transfer a table row from one table to another in AngularJS?

I need assistance with a feature that allows users to move rows between tables by clicking on buttons. When the 'up' button is clicked, the 2nd table row should be moved to the 1st table, and when the 'down' button is clicked, the 1st t ...

NextJS - Accessing local files with readdir and readFile functions leads to error: Module not found when trying to resolve 'fs' module

I have been working with NextJS and have successfully used the getStaticProps functionality in previous projects to populate data. However, I recently set up a new NextJS project and it seems that this functionality is no longer working. When starting th ...

Utilize Office Scripts to update values across numerous worksheets

Looking for ways to improve the performance of this script, as it currently takes 45 seconds to run. Any ideas? function main(workbook: ExcelScript.Workbook) { try { const sheets = workbook.getWorksheets(); for (let sheet of sheets) { const break ...

Applying CSS styles to a class dynamically using JavaScript

Is there a way to dynamically add a new CSS property to an existing class using JavaScript? Let's say I have a class called .test with some pre-defined styling. How can I append the property color: blue; to this class using JavaScript? const elm ...

The HTML5 webpage is failing to send a JQuery Ajax request

I am encountering an issue with my Ajax setup on a HTML page. The call to a web service does not seem to be working as intended, and I suspect that the ajax call is not even reaching the web service at all. The problem arises when I click the button, an e ...

Using Python's json.dumps() to write JSON data to a CSV file

While working on writing to a CSV file, I encountered an issue with dealing with a large JSON string in one of the columns. I am looking for a way to prevent the commas within the JSON from being treated as separate values in the CSV file. I prefer not to ...

When implementing AngularJS in a situation where the page layout is created by the user, what is the best

As I work on developing a web application, my main goal is to incorporate around 6 unique "widgets" that users can interact with. These widgets will serve different functions and users will have the ability to add, remove, and position them as they wish on ...

utilizing the volley library to load a JSON array

In the beginning, I fetch data from a web API in JSON array and extract what's inside the array. Then, I provide these two arrays (names, img_url) to a custom grid view to display to the user. However, my JSON array that is retrieved using the Volley ...

Using JavaScript with Selenium, you can easily clear the input field and send

Here is a question input field. When clicked on, the h3 element with the name will disappear and the input tag will appear for entry of a new name. <td style="width:92%;"> <h3 id="question_tex ...

`vue.js: li element tag numbers not displaying correctly`

Issue with Number list not displaying correctly using Vue.js I have tried sending it like this. Is there a fix for this problem? This is the code snippet I used to output in Vue.js: p(v-html="selectedProduct.description") Snapsho ...