Accept a JSON-sending POST request in a JSP file via JavaScript

I have developed an HTML page with an input field. Using javascript, I extract the input value, convert it into JSON format, and attempt to send it through ajax. Additionally, I have a JSP application where a Java method processes this JSON data to store it in a database. However, the challenge lies in receiving the ajax call in my JSP application and passing it on to the Java method. Can anyone offer guidance on how to achieve this?

Javascript:

alert("I am preparing to POST the following:\n\n" + dat);

$.ajax({
    url: '/path/to/file',
    type: 'POST',
    dataType: 'JSON',
    data: dat,
})
.done(function() {
    console.log("success");
})
.fail(function() {
    console.log("error");
})
.always(function() {
    console.log("complete");
});
`

JSP:

'<%@ page language="java" import="connection.JsonHandler" %>
<%
String json = request.getParameter("dat");;
JsonHandler gson = new JsonHandler();
gson.ReadJson(json);
%>

Java:

package connection;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.gson.GsonBuilder;
import entidades.User;
import java.lang.reflect.Type;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;

public class JsonHandler {
    public Gson CreateJson(String values) {
        Gson gson = new GsonBuilder().create();
        gson.toJson("Hello", System.out);
        gson.toJson(123, System.out);   
        return gson;
    }

    public void ReadJson(String json){
        Gson gson = new Gson();
        Type type = User.class;
        gson.fromJson(json,type);
    }
}

Answer №1

To handle your POST request, consider creating a servlet. Check out the following resources for more information: Troubleshooting POST value retrieval in servlet page or Guide on extracting data from ajax request in servlet page

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

Dropbox menu within an extended webpage

I am looking to create a dropdown menu that behaves like the one on this website. The goal is for the dropdown to cover the entire webpage, hide the scroll bar, and "unmount" the other elements of the page, while still displaying them during the transition ...

The range filter is exclusive to the initial controller

My range filter (see code below) is only working on my first controller. I have added the same filter to other controllers in the app.js and HTML, but it's not functioning for some reason. I checked the console for errors, but there are none. Here i ...

Get a collection of strings from a WCF service triggered by jQuery

After calling my service to retrieve a list of strings, I encountered an error message. $(document).ready(function () //executes this code when page loading is done { $.ajax({ type: "POST", url: "Services/pilltrakr.svc/getAllUsers", ...

What is the best way to show "no results found" message in a jQuery search list?

Everything is working smoothly. Does anyone have any suggestions on how to display a message saying "No results found"? This is the code I'm using: http://jsfiddle.net/UI_Designer/8p426fog/4/ $(".my-textbox").keyup(function() { var val = $( ...

Generate a request to load JSON data

On my webpage, I have several external JSON files that need to be loaded. I'm looking for a way to specify the order in which they should be loaded. Using JavaScript for this task, here is an example: const func1 = () => { $.getJSON(json1, re ...

How can this be happening? It's expected that items will be printed, but for some reason

I'm struggling to figure out why the console.logs aren't showing up. import { GenericRepository, getGenericRepository } from '../src/database/repository/GenericRepository'; import { start, stop } from '../src/index'; import r ...

What steps should I follow to have my edit form component extract values from HTML in Angular?

I created a detailed listing page that includes a picture URL, title, phone number, description, and price. When the user clicks on the Edit button, it redirects them to a page with input forms for each of these fields. The form automatically populates the ...

Responsive design element order rearrangement

My code example is as follows: <div class="info-container"> <span class="item1">item1</span> <a class="item2" href="#">item2</a> <a class="item3" href="#">item3</a> </div> I want to rearran ...

Preventing Vue.js from triggering watch on initial load

I need to implement a feature where a button is initially disabled and only becomes enabled when the input value is changed. To achieve this, I am using a boolean flag that is set to true by default and turns false only when the input changes. The v-model ...

WebPack bundling causing issues with Knockout Validation

I am developing a web application using Knockout along with the Knockout-Validation plugin, and I want to utilize WebPack for bundling. However, I encountered an issue where Knockout-Validation seems to break when incorporated with WebPack. To illustrate ...

In search of an effortless method to effortlessly select numerous elements using a handy bookmarklet

My goal is to develop a bookmarklet that can perform various functions on different webpages with ease. The concept involves placing it in a convenient location, such as the bookmark bar, and executing a "standard function" on a particular page. Instead of ...

The majority of the sliding banner is crafted using 90% HTML and CSS3, with just a touch

I devised a clever script to smoothly slide an image back and forth across the screen using CSS3. Unfortunately, I encountered a problem with CSS animations - they do not support changing the background-image directly. Attempting to overcome this limitatio ...

Create PDF files on-the-fly using the html-pdf module

Recently, I've been using the npm package html-pdf for generating PDF invoices dynamically. However, I encountered a problem where instead of saving values to the PDF file, it was saving ejs code. Does anyone have any insight on why this might be happ ...

How can you convert a JavaScript object with nested arrays into JSON format?

I have been working with a JavaScript object that contains nested objects with associative arrays. I attempted to use the stringify function from the json2.js library, but the output did not include the arrays inside the nested objects. In my scenario, I b ...

JavaScript and AJAX: Dynamically Create URLs

I don't have any experience with web development, so could you please explain in detail? If my questions are unclear, feel free to ask for more information. Imagine I have a webpage with the following URL: www.mycompany.com/category1 This page has ...

Mastering the art of Promises and handling errors

I've been tasked with developing a WebApp using Angular, but I'm facing a challenge as the project involves Typescript and asynchronous programming, which are new to me. The prototype already exists, and it includes a handshake process that consi ...

What causes the "undefined" error in Node.js when using a

Currently, I am utilizing the node-craigslist package for scraping listings from craigslist. However, I have encountered an issue when processing the results. client .search(options, '') .then((listings) => { listings.forEach((listing ...

Completing online form text entries in WebView without the need for identifying elements

I am currently working on a project to automate filling out an online login form using local string variables. This is the progress I have made so far: web = (WebView) findViewById(R.id.webview); WebSettings webSettings = web.getSettings() ...

Implementing auto-complete functionality for a text box in an MVC application using jQuery

After incorporating code for auto completion in a text box using AJAX results, the following code was utilized: HTML: <div class="form-group col-xs-15"> <input type="text" class="form-control" id="tableOneTextBox" placeholder="Value" > ...

Could someone share an instance of an AngularJS configuration that continuously checks for new data and automatically refreshes the user interface once the data is obtained?

Struggling to find a suitable example for this scenario. I am looking to create a chart directive that will be updated every minute by fetching data from a web service. Currently, I have a service that acts as a wrapper for the web service. My controller ...