Managing JSON responses in the client-side view technology of SpringMVC

I have been struggling to implement the following scenario using Spring MVC. I am encountering issues and unable to determine the correct approach. My implementation involves jsonRequest/jsonResponse (Restful Web services).

1. I have a SignUP.jsp Form with multiple fields that need to be submitted to the controller.


<form method="POST" onsubmit="javascript:signupObj.signup()">
<table>
<tr>
<td>Username :</td>
<td><input id="username"/></td>
</tr>
<tr>
<td>Password :</td>
<td><input id="password"/></td>
</tr>
<tr>
<td>
<button type="submit">Submit</button>
</td>
</tr>
</table>
</form>

2. Upon submission of the form, it will invoke the signup Javascript function as mentioned below:


var signupObj = {
showSignup: function() {
        $.ajax({
            type: "GET",
            url: "showSignup",
            success: function(response) {
                $("#signupView").html( response );
            }
        });
},
signup: function() {
     // Signup function code
}
redirectview: function(message,data) {
    // Redirect view function code
}
};

3. The above JavaScript function makes an ajax call to the controller using jsonResponse as input.


// Controller methods for signup and success views

4. The Controller response returns a JSON object. Based on the profileDTO.getErrors, loginSuccess.jsp or loginFailure.jsp needs to be called.

My Questions are:

1) How can I use jsonResponse in ajax calls to redirect to loginSuccess.jsp or loginFailure.jsp and pass my profileDTO data to the loginSuccess view?

2.) Please suggest the best practices to be followed in this scenario.

Answer №1

1.) To start, simplifying your JavaScript code can be done by directly serializing the form object like this:

var signupObj = {
    signup: function() {   
        alert("In Signup function");
        $.ajax({
            type: "POST",
            url: "signup",
            data: $('#myForm').serialize(),
            async: false,
            success: (function(data) {
                alert("data"+data);
                redirectView("success", data);
            }),
            error: function(data, textStatus, errorThrown) {
                alert(error_occured);
                redirectView("error", data);
            }
        });
    }
};

<script
function redirectView(message,data){
    var url = "";
    if(message == "success"){
        url = "/success";
    }else{
        url = "/error";
    }

    $.ajax({
        type: "POST",
        url : url,
        data: data 
        async:false,
        success: (function(data) {
            alert("data"+data);

        }),
        error: function(data, textStatus, errorThrown) {
            alert(error_occured);
        }
    });
}
</script>

2.) Handle the redirection to success or failure view from the controller itself.

3.) Make sure to pass profileDTO data to the loginSuccess view.

Starting from version 3, Spring MVC provides the ability to return objects directly converted into JSON using the @ResponseBody annotation in a Controller, as shown below:

@RequestMapping(value="/signup", method=RequestMethod.POST)
@ResponseBody
public ProfileDTO signup(@ModelAttribute("LoginDTO") LoginDTO loginDTO, BindingResult bindingResult) {
    ProfileDTO profileDto = new ProfileDTO();
    // Add backend logic here
    profileDto.setError(null);
    profileDto.setProfileID("profileID");
    profileDto.setProfileName("profileName");
    System.out.println("Submitting SignUP Form Will Return ProfileID");
    
    return profileDto;
}

If Forwarding from the controller

By prefixing with forward, Spring will obtain a RequestDispatcher for the specified path and perform a forward action. This process involves transferring the Model attributes from the ModelAndView created for that request handling cycle into the HttpServletRequest attributes.

The DispatcherServlet will handle the RequestDispatcher#forward(..) action, creating a new ModelAndView with a fresh Model. Therefore, the new Model won't contain any previous attributes but they can still be accessed via the HttpServletRequest attributes.

In your scenario, the following:

modelMap.put("key", "value");

will end up being accessible within the HttpServletRequest attributes like:

HttpServletRequest request = ...;
request.getAttribute("key");

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

Navigating the jQuery Search Form: Redirecting to Pages within your Website

After successfully creating my first Javascript search form with an Autocomplete Script, I am facing a challenge. I want to enable users to press "enter" after searching for a product and get redirected to the corresponding product URL page. The operation ...

Parsing a JSON array containing a combination of fields and dictionaries

I need assistance in creating a C# class to deserialize the following JSON using Newtonsoft.Json: [ { "awb": "2205900120010", "oras destinatar": "", "continut": "", "nume confirmare": "", "data confirmare": "", ...

Do not meddle with JSON encoding without 'require_once'

Utilizing AJAX to trigger my validation.php file, I encountered an issue when trying to connect to the database by including the connect.php file. <script type="text/javascript"> $(document).ready(function(){ $("#offer-form").submit(function(e){ ...

Display the initial page and activate the first navigation button when the page loads

Greetings to everyone. I am new to the world of jquery and currently in the process of learning. This is my script: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"> </script> <script> $(function () { $ ...

Accept two parameters for password change

Is there a way to include two values, one being the selected value and the other a PHP variable, in a dropdown select element's onChange function? For example: <div> <?php $sql4 = "SELECT DISTINCT (color), id ...

Iterating over each element in a ForEach loop to increment its value

Seeking assistance with arrays and increments. I've created a function that applies the same style to each new element in an array: function SnakeBodyLeft(){ StorePositions.forEach(BodySnake => { BodySnake.style.gridRowStart = (Initial_y + y ...

Is there a way to access the history of Vue routers?

I am looking for a way to determine if the Vue router has additional entries in its history that can be navigated back to. This information is crucial for deciding whether or not to execute the exit app function. The app should only navigate back to prev ...

Creating dynamic transformations and animations for characters and words within a paragraph in 3D

Looking to add animation effects to specific parts of a paragraph, but transforming the entire box instead. Remembering seeing a solution on StackOverflow before, now regretting not saving it. Spent over an hour searching for a similar answer without succ ...

Reflections on Javascript MVC Architecture

Here is my design of MVC utilizing JavaScript. I made a conscious effort to avoid using any MVC frameworks to achieve a clear structure and decoupled organization. What are your thoughts on my approach? I am considering incorporating something like requir ...

Utilizing jquery and ajax to showcase a series of images prior to uploading them

I have been attempting to create a feature that allows for the preview of multiple images before uploading them to my website. Unfortunately, it's not working as expected and I am unable to identify any errors in the console. Below is the JavaScript c ...

Differences between REST and RPC in PHP

As I work on my Ajax website, I find myself pondering the choice between using REST or RPC. If only my server supported Servlets, I could easily solve this dilemma by installing persevere. Unfortunately, that's not an option with my current server se ...

I possess an RSA encrypted private key along with a passphrase. Can you guide me on decrypting the private key file

I'm looking to execute this command in Java: openssl rsa -in enc_private.key -out private.key -passin pass:passphrase_xyz The encrypted key file I have starts like this: -----BEGIN RSA PRIVATE KEY----- Proc-Type: 4,ENCRYPTED DEK-Info: DES-EDE3-CBC,59 ...

Is there a way to set columns as initially hidden in MaterialTable?

I have a MaterialTable with many columns, and some of them are not always necessary to display. I am looking for a way to hide these columns unless the user specifically selects them. I attempted to use the hidden: true property in the column configuratio ...

Exception thrown by ASP.Net Javascript code persists despite being commented out!

In my ASP website, I have incorporated Javascript code in the HEAD section to create a custom context menu. Here is the logic that I initially used: function fileGridGrouping_ContextMenu(s, e) { if(e.objectType != "row") return; fileGridGrou ...

Managing toggles for save and edit buttons in Vue - a comprehensive guide

I am currently working on a Vue 'app' within a larger Django application as a means to enhance my understanding of Vue. My objective is to create unique forms that can be edited independently. I have been experimenting with this for some time n ...

A guide on looping through data in a JSON-serialized System.Data.DataTable with the help of jQuery

Here is an example of the JSON format: [ {"animal":"dog", "sound": "bark"}, {"animal":"cat", "sound": "meow"} ] I am looking to iterate over each record {...} within the brackets [ ], starting with the dog-record and then moving on to the cat- ...

Import a 3-dimensional object from an .obj file and adjust its positioning within the camera view using Three.js

I am currently working on dynamically loading object files using THREE.OBJLoader and positioning them in the center of the scene or canvas to ensure the entire object is visible in the camera view. Since the objects are dynamic, I do not have fixed height ...

Reading small JSON files from android assets experiences a significant lag

Currently, I am developing a straightforward Android application in Kotlin that will display categorized prayers to the user. In the assets folder, there are 5 JSON files, each approximately 10 KiB in size. For parsing these JSON files, I am utilizing Kla ...

Creating a function to wrap the return type of an AJAX call within the success method

My Web Service consistently returns one object from a class I defined on the server side. When using the $.ajax function's success method, I always receive this object. On the client side, I am looking to add some functions for quickly displaying its ...

Deletion of an element with Reactjs upon clicking

A photo gallery consists of a collection of photos with corresponding delete buttons. Below is the HTML snippet for a gallery containing two images: <div> <div class="image"> <img src="URL1"> <button class="remove">X</ ...