Using @modelAttribute in an Ajax request in a Spring application

Currently, I am utilizing an ajax call to submit a form, but facing difficulties in accessing the parameter as a model attribute.

Ext.Ajax.request({
                url: 'url',
                headers: { 'Content-Type': 'application/json' },
                params : Ext.JSON.encode(form.getValues()), //this is the parameter in jason pattern

                success: function(response, options) {
                    var result = Ext.JSON.decode(response.responseText, true);

                    if (result.success) {

                        Ext.Msg.show({
                            title:'DataBase',
                            msg: result.message,
                            buttons: Ext.Msg.OK,
                            icon: Ext.Msg.INFO
                        });

I have a question - is it possible for me to access this parameter as a model attribute similar to the code snippet provided below?

@RequestMapping(value="/employee/new", method = RequestMethod.POST )
@ResponseBody public String doAddEmp(@RequestBody String Str){
    try{
        empServ.setError();
        if(empServ.addEmp(Str)){
            return "{success:true, message:'Insertion Successfull'}";
        }else
            return "{success:false, message:\""+empServ.returnError()+"\"}";

    }
    catch(Exception e){
        e.printStackTrace();
        return "{success:false, message:'SQL ERROR'}";

    }

}

I would greatly appreciate any useful suggestions regarding my query. If the current pattern for the parameter is incorrect, kindly recommend the appropriate pattern.

Answer №1

It seems like there might be some confusion between @ModelAttribute and @RequestBody in your code snippet. While both are used for binding data, @ModelAttribute is typically used to access model attributes while @RequestBody is used for accessing request body data.

For Ajax requests, using @RequestBody is recommended, as shown in the provided code sample.

To ensure everything works smoothly:

  • Check that Ext.Ajax.request has "method: 'POST'"
  • Make sure your controller is annotated with @RestController
  • Update "@RequestBody String Str" to "@RequestBody Employee employee"
  • Verify that the names of your form elements match the fields of the Employee object

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

Show the time in hours and minutes (00:00) while rounding off seconds to the nearest minute

I need the time to always display with leading zeros when less than 10. For example, if a task took 3 hours, 7 minutes, and 33 seconds, it should be shown as 03:08. Currently, I have the buttons disabled after they are clicked to prevent restarting the ti ...

AngularJS - "Refrain from replicating items in a repeater"

I am facing an issue with creating HTML textarea elements for each member of an array. Despite consulting the AngularJS documentation and attempting different track by expressions, I am unable to render them. The problem arises when a user inputs the same ...

How can I assign a URL when a button is clicked in Next.js?

Can I manipulate queryString values using nextjs and reactjs? I have a filter list on my page that changes the displayed results when clicked. I want to update the URL's queryString values so that if a user navigates away from the page and then retu ...

The React Native SearchBar is throwing an error: It is stating that the prop type `value` being passed to `ForwardRef(TextInput)` is invalid. The expected type is `string`, but

I'm completely lost with this error message. Everything was running smoothly a while back, and I haven't made any changes to this code. When I returned to this page recently, I was greeted with the following error: Failed prop type: Invalid prop ...

Tips for locating 2 geopoints in mongodb with the help of mongoose

Currently, I am working on a project that uses NodeJS with the Mongoose driver for the backend and MongoDB as the database, along with Angular 6 for the front end. One of the requirements is implementing a feature to search for data using two geoPoints. Ho ...

Center-align the text in mui's textfield

What I'm looking for is this: https://i.stack.imgur.com/ny3cy.png Here's what I ended up with: https://i.stack.imgur.com/vh7Lw.png I attempted to apply the style to my input props, but unfortunately, it didn't work. Any suggestions? Than ...

Flaw in Three.js POV camera causing issues with looking around

In my latest project with three.js, I have created a simple scene and my aim is to implement a point of view camera based on FirstPersonControls.js. I made some adjustments to the code in order to customize it according to my requirements like moving the ...

JavaScript code causing the page to freeze

I am attempting to track the movement of a dynamic div (which is animated using CSS3 animations) by continuously monitoring its position. To achieve this, I have implemented a loop utilizing while(true) as shown below: function detectCollision(){ ale ...

Utilize Ajax to invoke a function simultaneously with another Ajax call that includes preventDefault to submit the data

I am currently implementing two AJAX calls within my form. The first call is used to dynamically update the options in the second select element based on the value selected in the first select element. This call reaches out to a PHP page to process the dat ...

Unable to access specific data from the JSON string retrieved from the backend, as it is returning a value of undefined

After receiving a JSON string from the backend, my frontend is encountering issues when trying to index it post using JSON.parse(). The indexed value keeps returning as undefined, even though it's a JSON object literal and not within an array. For th ...

The dd accordion feature seems to be malfunctioning as it is not working as expected

I'm having an issue with a ddaccordion setup on my website. It seems to stay open all the time instead of functioning as expected. I've double-checked that the correct library is being called and there are no error messages in the console. To tr ...

Ways to retrieve the value of an Object that may have a key that is undefined

Is there a method similar to Angular's $parse service that can be used for accessing nested object properties? Consider an object structure like this: const obj = { items: [ { store: { type: '' } } ] }; Sce ...

Even though all criteria are met, I still cannot assign a value to the property following the application of the filter method

const selectSeatEventCallback = ( price, flightNum, segmentKey ) => { var postData = { ...state.post }; postData.IsSeatChosen = true; postData.AirPassengerList.filter( (passenger) => ...

Display a nested modal within a modal, where the second modal automatically closes itself. Innovative feature in IONIC 3

Currently, I am working with Ionic 3 and facing an issue where a modal is unexpectedly closing on its own. The scenario involves opening one modal inside another - the first modal contains pre-filled form data and if the user wishes to clear it, a second m ...

The @Configuration annotation on the method before necessitates the definition of the 'browserType' parameter, which is missing in the src est esources estng.xml file

During my Selenium test, I encountered an issue where both Firefox and Chrome were not on the same build version. Here is a snippet of my testng.xml file: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0 ...

Leveraging the power of dual layouts in Nuxt 3

I've encountered an issue with my /profile page setup. It utilizes a profile layout for common elements like the sidebar, but I also have a sub-page at /profile/favorite. My goal is to incorporate both the default layout (with a header and footer) and ...

JQuery continuously firing off AJAX requests

Currently, I am experimenting with using a Jquery Ajax request to incorporate an AutoComplete feature. This involves utilizing ElasticSearch on the backend for data retrieval. This is what my autocomplete.html looks like: <!DOCTYPE html> <html l ...

How to efficiently transfer data between Node and Angular 7 using Electron

After setting up an Angular 7 application running on http://localhost:4200, I developed a Node JS application responsible for authenticating users on Facebook, accessible at http://localhost:3000. The callback redirection functions correctly within the No ...

Utilizing shared code amongst React components

There are several components with methods similar to the ones below: class Header extends Component { sidebarToggle(e) { e.preventDefault(); document.body.classList.toggle('sidebar-hidden'); } sidebarMinimize(e) { e.preventDe ...

Issue with pointer events: pointercancel triggered by pressure-sensitive input (stylus)

Seeking your assistance in resolving an issue that I am facing while developing a web app in Chrome using React and Canvas. It appears to be related to the PointerEvent, specifically with pressure pen input. The Problem: When I attempt to draw with my tab ...