Is there a way to transfer JSON data from a JSP page to a Spring REST controller efficiently?

Attempting to send data from a jsp page containing datetime, zoneid, checked checkboxes with values, and unchecked checkboxes with null values.

Despite sending all this as json to my spring rest controller, I noticed in debug mode that the controller only received two pieces of data (one checkbox that I clicked and the submitted input value). It's puzzling where the rest of the data disappeared to.

While sending data through postman works flawlessly, I'm encountering difficulties when trying to send it from the jsp page.

Prior to this, I used @RequestBody in the controller to retrieve data of type pojo class object, but it resulted in a content-type unsupported error. I then switched to using @RequestParam for map type data, which resolved the error. However, the reason behind the initial error remains unclear.

jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
       pageEncoding="ISO-8859-1"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<!-- Static content -->
<script
       src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" href="/resources/css/style.css">
<script type="text/javascript" src="/resources/js/app.js"></script>
</head>
<body>
   <script
       src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

 <form   id = "schedulejob" action="scheduleJob" method="POST">
<label>
<input type="checkbox"  id = "corporateClientCare" name="corporateClientCare" value="corporateClientCare" class="input_checkbox"> CorporateClientCare 
</label>
<label>
<input type="checkbox" id = "dayforce" name="dayforce" value="dayforce" class="input_checkbox"> Dayforce  </label>
<label>
<input type="checkbox" id = "tss" name="tss" value="tss" class="input_checkbox"> TSS </label>
<label>
<input type="checkbox" id = "multimax"  name="multimax" value="multimax" class="input_checkbox"> Multimax</label>
<label> <input type="checkbox" id = "arcot"  name="arcot" value="arcot" class="input_checkbox"> Arcot <br/></label> 
<input type="datetime-local" id="dateTime" name = "dateTime" value="2019-06-04T15:25:33">    
<input type="submit" name="Scheduler" value="Scheduler" class="submit"/></form>

<script>
jQuery(document).ready(function($) {
$("#schedulejob").submit(function(){
var scheduleRequest = {};
scheduleRequest["corporateClientCare"] = verifychecked("corporateClientCare");
scheduleRequest["dayforce"] = verifychecked("dayforce");
scheduleRequest["tss"] = verifychecked("tss");
scheduleRequest["multimax"] = verifychecked("multimax");
scheduleRequest["arcot"] = verifychecked("arcot");
scheduleRequest["dateTime"] = document.getElementById("dateTime").value;
scheduleRequest["timeZone"] = "Asia/Kolkata";
$.ajax({

type : form.attr('method'),
contentType : "application/json;charset=utf-8",
url : form.attr('action'),
data : JSON.stringify(scheduleRequest),
dataType : 'json',              
success : function(data) {

                    }
                });
         });

        function verifychecked(value) {
        var varr = '';
        if(document.getElementById(value).checked)
        {
           varr = value;
        }
        else{
            varr = null;
        }
          return varr;

    }
    });
    </script>   
</body>
</html> 

controller

@Autowired
    private Scheduler scheduler;

@PostMapping("/scheduleJob")
public ResponseEntity<ScheduleResponse> scheduleJobs(@RequestBody ScheduleRequest  scheduleRequest) {
    try {
        System.out.println("___________IN CONTROLLER__________");
        System.out.println("--------------zone-----------");
        ZonedDateTime dateTime = ZonedDateTime.of(scheduleRequest.getDateTime(), scheduleRequest.getTimeZone());
        System.out.println("--------------date is-----------" + dateTime);
        System.out.println("dateTime is " + dateTime);
        if(dateTime.isBefore(ZonedDateTime.now())) {
            ScheduleResponse scheduleResponse = new ScheduleResponse(false,
                    "dateTime must be after current time");
            System.out.println("--------------1-------------------");
            return ResponseEntity.badRequest().body(scheduleResponse);
        }
//rest code

Despite thorough checks in debug mode, the map only contained 2 keys, leaving me puzzled about the missing data.

Answer №1

If you have included the action and method parameter in the form, as well as a submit button, then clicking the submit button will trigger a POST request with the default content type of

application/x-www-form-urlencoded
. If you want to change this to JSON, you can use the enctype attribute like this:

<form method="post" enctype="multipart/form-data">

Unfortunately, HTML does not provide a way to generate JSON from form data. To handle this on the client side, you will need to use JavaScript.

You will need to disable the HTML form submit, collect the data, and then use jQuery AJAX to send a post request with the content type set as application/json.

You can try the following jQuery code to trigger the form submit:

$("#schedulejob").on('submit',function( event ) { 

event.preventDefault();

var scheduleRequest = {};
scheduleRequest["corporateClientCare"] = verifychecked("corporateClientCare");
scheduleRequest["dayforce"] = verifychecked("dayforce");
scheduleRequest["tss"] = verifychecked("tss");
scheduleRequest["multimax"] = verifychecked("multimax");
scheduleRequest["arcot"] = verifychecked("arcot");
scheduleRequest["dateTime"] = document.getElementById("dateTime").value;
scheduleRequest["timeZone"] = "Asia/Kolkata";

$.ajax({

type : form.attr('method'),
contentType : "application/json;charset=utf-8",
url : form.attr('action'),
data : JSON.stringify(scheduleRequest),
dataType : 'json',              
success : function(data) {

                    }
                });
         });

        function verifychecked(value) {
        var varr = '';
        if(document.getElementById(value).checked)
        {
           varr = value;
        }
        else{
            varr = null;
        }
          return varr;

  }); 
});

In your code, you were not passing the 'event' to the function. According to the jQuery documentation, you should do that. Refer to this link for more information.

Alternatively, instead of using an input type submit button, you can use the following:

<button type="button" id="submitBtn">Submit Form</button>

$(document).ready(function(){
$("#submitBtn").click(function(){        
   // Submit the form using jQuery as shown above
});
});

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

Stop automatic form submissions from the enter key

My live chat messaging system is experiencing an issue where the page refreshes every time a user presses the enter button. I attempted to use prevent default code, but it did not work for me. I'm new to website programming, so if there are any proble ...

Automatically relaunch NodeJS application upon app failure

I am looking for a way to automatically restart my NodeJS (Express) app after crashes with errors. I am familiar with the forever npm package, but all the examples I found were for running the app in development. My goal is to implement this in production ...

"Creating a Typescript array by extracting items from a different const array (as seen in the official beginner tutorial

Currently, I am working through the Angular tutorial that can be found at https://angular.io/start. After successfully completing the tutorial, I decided to practice building for production locally. However, when attempting to build, I encountered this err ...

Tips on sending data with a unique identifier to the backend through a route parameter

Can anyone help me figure out how to send a message to a specific backend route parameter while passing the current ID? I'm not sure how to inform the system about this ID. Here's the Vuex action: postMessage({commit}, payload, id) { axios.pos ...

How can values be extracted from a multi-dimensional array using JSON.parse()?

Here is a JSON array before using JSON.parse: var temp = { "queries": [ { "sample_size": 3, "results": [ { "name": "temperature", "tags": { "Tag": [ "temperature" ] ...

Darken the entire webpage and gradually fade in a specific div element using Jquery

Currently, I am working on implementing the following functionality: - When a link is clicked, it should trigger a function to show a DIV (#page-cover) that will dim down the entire background. This div has a z-index of 999. - Following the dimming effect, ...

The function 'myfunc' was called within a render, however, it is not defined in the instance

I keep seeing this error message Property 'myfunc' was accessed during render but is not defined on instance, and I'm not sure why. Below are my HTML and JavaScript code snippets. const ListRenderingApp = { data() { return { todo ...

Upon refreshing the page, nested React routes may fail to display

When I navigate to the main routes and their nested routes, everything works fine. However, I encounter an issue specifically with the nested routes like /register. When I try to refresh the page, it comes up blank with no errors in the console. The main r ...

Text that changes within a set-sized box

I'm working with a fixed-size div that contains dynamically generated text. Is there an easy method using DOJO or plain Javascript to truncate the text before the end of the div and add "..."? How can I accomplish this regardless of the font size bein ...

My attempt at utilizing the regex function was unsuccessful

When attempting to use a regex function for matching tags in the title and caption, it appears to work fine. However, adding more matching tags causes the function to fail. Below is the code snippet that functions correctly without any issues: $(".si ...

How to Retrieve JavaScript Array Data Using Ajax in a Wordpress Plugin and Store it in a PHP

function my_custom_js_action($value1, $value2) { ?> <script type="text/javascript" > jQuery(document).ready(function($) { var newData = { 'email': '<?php echo $value1?>', 'p ...

When there is a lack of internet connection, WKWebView does not reach completion or timeout

When using a WKWebView to navigate to a local HTML page, I encountered an issue with a remote Javascript asset tag that never finished downloading. This occurred even when the iOS device was not connected to the internet or had slow internet speeds. The p ...

Passing a selected value from the child to the parent component through state in React using hooks

I'm currently working on a Dropdown component that includes a select tag. When the user changes the value in the select, the state is updated to reflect the selected option. The StyledDropdown component is used for styling the select element. const D ...

The HTML table fails to refresh after an Ajax request has been made

I am currently utilizing Ajax to delete a row from the Roles table. The functionality allows the user to add and delete roles using a link for each row. While the deletion process works properly and removes the row from the database, the table does not get ...

Steps on how to set the values of a select option based on a JSON parsed array

After receiving an array from a JSON call, I am trying to populate a select element with the data. {1:Android, 2:IOS, 3:Business Management Systems, 4:Database, 5:Codes/Scripts, 6:Others} or 1: "Android" 2: "IOS" 3: "Business Management Systems" 4: "Da ...

verifying the structure of JSON schema with embedded components

As I work on crafting a JSON schema, my goal is to ensure that 'ewb_query' is an object with string values. It's important for me to clarify that any keys are acceptable, not limited to just name and age like in the provided example. For in ...

Instructions on establishing a connection with a MongoDB server using JavaScript

Hello all, I am a complete beginner when it comes to working with mongodb and java script. I am currently trying to figure out how to establish a connection to my local mongodb instance using java script so I can retrieve a list of documents. Does anyone ...

"How to automatically populate an input field with a value when the page loads in an

I need assistance with setting the input value to 1 when the page is loaded, but for some reason, it remains empty. Can someone help me troubleshoot this issue? <tr *ngFor="let item of cartItems; let i=index"> <td class="cart_pr ...

encounter an auth/argument issue while using next-firebase-auth

Issues: Encountered an error while attempting to log in using Firebase Authentication. No errors occur when using the Firebase Auth emulator, but encountered errors without it. Received a 500 response from login API endpoint: {"error":"Unex ...

Passing a method as a parameter type

As I delve into learning JavaScript from Objective-C, I find myself pondering whether it is possible to have a method with parameter types in Objective-C. Let's take the example of the findIndex() JavaScript function that identifies and returns the in ...