Sending a request to the controller via AJAX in order to transfer data from a JSP webpage

I'm new to Spring MVC and encountered an error while trying to pass data to a controller using Ajax. Please review the code below and provide any potential solutions.

 <form class="form-horizontal bucket-form" id="myform" method="post" >
            <div class="control-label text-center">
               <p class="required"><em>required fields</em></p></div>

                <div class="form-group">    
                    <label class="col-sm-3 control-label required">First Name</label>
                    <div class="col-sm-6">
                        <input type="text" name="firstname" id="firstname" class="form-control">
                    </div>
                </div>
                 // Other input fields...

                <div class="form-group">
                    <div class="col-lg-offset-3 col-lg-6">
                        <button class="btn btn-primary" id="speakerSubmit" type="submit">Save</button>
                     // Script for form reset...
                    </div>
                </div>

            </form>
        </div>
    </section>      
    </section>

    <div class="footer">
           <div class="row">
                <div style="float:left" class="col-md-6"><p 
  style="padding:15px">© 2017.All rights reserved | Powered by <a 
  href="www.techmahindra.com"> TechMahindra </a></div> </p>
                      // Social media icons...
            </div>
    </div>

 </section>
 <script src="js/jquery2.0.3.min.js"></script>
<script 
 src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
 // Other script files...

<script>
$( document ).ready(function() {
// AJAX request function...
 });
 </script>

Speaker Class

// Speaker class definition...

    }

SpeakerController

Description of Speaker Controller...

 // Speaker controller with annotation mappings...
 

SpeakerserviceImpl

 // Service implementation for adding a speaker...

SpeakerdaoImpl

 // Implementation of DAO layer for handling speakers in the database...

Error Result

The Request sent by client is syntactically incorrect status-400

Answer №1

Controller

@PostMapping("EMS_APP/spkr")
public ResponseEntity addSpeaker(@RequestBody SpeakerAddRequest request) {
    Speaker speaker = new Speaker();
    speaker.setFirstName(request.getFirstName());
    ...
}

A breakdown of the code

  • The annotation @PostMapping is shorthand for

    @RequestMapping(method = RequestMethod.POST)
    .
    The specific mapping to URL and HTTP method is defined by @PostMapping("EMS_APP/spkr"), equivalent to
    @RequestMapping(value = "EMS_APP/spkr", method = RequestMethod.POST)
    .

  • @RequestBody plays a role in mapping the payload of a POST request to a Plain Old Java Object (POJO) like SpeakerAddRequest.

  • An example of correct usage, @RequestParam handles parameters in the URL rather than request body.

    // For a GET request with URL ../EMS_APP/spkr?name=foo
    
    @GetMapping("EMS_APP/spkr")
    public ResponseEntity<Speaker> getSpeakerByName(@RequestParam("name") String speakerName) {
        // speakerName== "foo"
    }
    

Data transfer object (DTO)

public class SpeakerAddRequest {

    @JsonProperty("firstname")
    private String firstName;
    ...

    public String getFirstName() {
        return firstName;
    }
}

Understanding the DTO

This section illustrates how the properties from the POST payload are mapped to the corresponding attributes in the POJO. With "firstname": "John", private String firstName is assigned as the key matches the one specified in @JsonProperty.

Form Handling

Enhance your ajax functionality

$.ajax({
    ...
});

by utilizing

$.post("EMS_APP/spkr", $("#myform").serialize());

The essence of form handling

Rather than tediously mapping all form elements yourself, this technique automatically structures the form data into a suitable format for submission via POST request to the designated endpoint.

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 Material UI library is signaling that there is an unidentified property called `selectable` being used with the <table> tag

Whenever I try to add the selectable attribute to the Table component in Material-UI using React JS, I encounter an error. Despite checking that selectable is indeed included in TableProps, the issue persists. List of Dependencies : "material-ui": "1.0.0 ...

The issue arises when Gradle fails to resolve a placeholder from the parent properties for a dependency version within a specified library in the build.gradle file

I have a question regarding resolving dependency versions using gradle. My scenario involves deploying libraries to Nexus. During this process, I utilized the flatten-maven-plugin and resolvedCiFriendliesOnly flattenMode, resulting in parent POM files and ...

Update the parameter value in a URL using JavaScript

I have a URL similar to this one here. something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false The parameter I'm interested in is showHiddenElements, and I would ...

Presenting a ui-router modal while maintaining the parent state's refresh-free appearance

I have implemented a unique feature in my angular app called modalStateProvider. It allows me to easily have modals with their own URLs. // Implementing the modalStateProvider app.provider('modalState', [ '$stateProvider', function ...

Display a separate component within a primary component upon clicking a button

Looking to display data from a placeholder module upon component click. As a beginner with React, my attempts have been unsuccessful so far. I have a component that lists some information for each element in the module as a list, and I would like to be ab ...

Clearing all the nested offspring elements within a highly nested one-dimensional array

I am working with a 1D deep nested array structure: nestedObj: [ { id: 1, parentId: null, taskCode: '12', taskName: 'Parent one', duration: 0, assignee: '', crewCount: 0, startDate: null, endDate: null, dependencies: []}, ...

What is the purpose of using $ symbols within NodeJS?

Lately, I've been attempting to grasp the ins and outs of using/installing NodeJS. Unfortunately, I'm feeling a bit lost due to tutorials like the one found here and their utilization of the mysterious $ symbol. Take for instance where it suggest ...

What are the steps to manually activate input validation in Angular 2?

Having two inputs is the scenario here: The first input undergoes custom validator application The second input has a dynamic and editable value utilized in the custom validator If the custom validator is applied on the first input, then focus shifts to ...

Should I load the data into an object after it's created, or should I directly get an instantiated object with the data already loaded?

When developing a webapp, I have a data-model called Item that is filled by two methods. The first method involves using an XML parser for data import, while the second method reads the data from a database during website parsing. There are two potential ...

Using AJAX to write a JSON file in PHP

How can I properly send data via jQuery/Ajax to a JSON file and receive it as a JSON object? The current format of my JSON content is: foo=abc&bar=def But I would like it to be in this format: { "foo" : "abc", "bar" : "def } HT ...

Utilize String to Set Cookies

My goal is to utilize requestjs for making requests and sharing cookies across various JavaScript files and servers. To achieve this, I have chosen to store the cookies in a database as a string and retrieve them when necessary. The string format aligns w ...

What is the best way to retrieve a string from a URL?

Is there a way to extract only a specific string from a URL provided by an API? For instance: I'm interested in extracting only: photo_xxx-xxx-xxx.png Any suggestions on how to split the URL starting at photo and ending at png? ...

Adding a button in Node and Mongoose for updating data: A step-by-step guide

I have set up a mongoose database containing events, each event is displayed within a bootstrap card. My challenge now is to find a way to redirect the admin to a page where they can update the event card and save it to my mongoose db. The problem I' ...

Transmit information to the controller using jQuery in a C# MVC environment

Here is my jQuery script code snippet. The script works perfectly and stores the data array/object in a variable called dataBLL. var dataBLL = []; $('#mytable tr').each(function (i) { dataBLL.push({ id: $(this).find('td:eq(0)').text( ...

Modifying an image's height and width attributes with jQuery and CSS on click action

I'm currently developing a basic gallery using HTML, CSS, and jQuery. The objective is to have a larger version of an image display in a frame with an overlay when the user clicks on it. While this works flawlessly for horizontally-oriented images, ve ...

Ng2-smart-table: Utilizing Angular 2 for Efficient Data Organization with Identically Named Columns

Here is a snippet of code where I am trying to display columns from a table: products: { title: 'Prodotto', filter: false, class: "colonneTabella", width: "15%", ...

What is the best method for enabling CORS policy when making a fetch request from a Vue.js frontend to

I am currently facing an issue with my front-end code that is making a request to the back end (frontend is running on localhost:8081 and sending a request to localhost:8080) This is the front-end code snippet: <script lang="ts">import &a ...

Looping through images using JQuery

I'm struggling with an image animation and can't quite figure out how to make it work. <div id="img_loop"> <img src="img/img1.jpg" alt="image1" /> <img src="img/img2.jpg" alt="image2" class="hidden" /> <img src="im ...

Dynamically allocate a controller to an element following the Bootstrap process

I have a unique AngularJS application that is initialized manually at a specific time. Later on, I need to display an HTML element without any ng-controller assigned to it. Is there a way to dynamically add an ng-controller to this element in order for it ...

How to connect multiple HTTP requests using observables in Angular 7

Is there a more efficient way to remove an alert only if it is not assigned to any user? Currently, I am checking my users list and filtering out the users who have this alert assigned using observables. But I wonder if there is a better approach to achi ...