Looking for a sophisticated approach in Spring MVC to manage the escaping and unescaping of strings being passed to the Front End

Currently, I am in the process of developing a web application utilizing Spring MVC. This project involves retrieving multiple objects from the Database, each containing strings as attributes. It's worth noting that I have no control over the format of these strings entered into the database.

However, I encountered an issue when passing strings with quotes (" and ') as part of JSON Objects to JavaScript. These special characters weren't being recognized correctly and were causing problems by prematurely closing the string they belonged to. To resolve this, I implemented a workaround by invoking the JavaScriptUtils.javaScriptEscape() function on every string retrieved from the database within a wrapper function.

While this fixed the JavaScript errors, it introduced another problem - now the escape character '\' was displaying alongside the strings on the webpage (e.g., " displayed as \" etc). In light of this, here are my current requirements:

  1. I require a function to 'unescape' these strings and restore them to their original form for proper functionality.

  2. I need a method to automatically apply this unescaping function to all strings fetched in the frontend, as manually calling this function for each attribute of every JSON object during AJAX calls is cumbersome. Additionally, I anticipate adding more features to the application in the future, so ideally, the solution should not entail hardcoding it into every AJAX request.

  3. I seek a more efficient approach to implement escaping on the database-fetched objects. Currently, I have a separate function for each object type to perform the escapes, but this means defining a new function whenever a new object type is retrieved.

I'm wondering if there might be a way to automate this process within Spring MVC, given that many developers likely encounter similar issues at some point. Any suggestions to streamline this workflow would be greatly appreciated!

EDIT:

This is the EscapeJS function used on every database-fetched string:

String EscapeJS(String string)
{
    string = JavaScriptUtils.javaScriptEscape(string);
    return string;
}

Here is how the objects are returned:

@RequestMapping(value = "/urlToController", method = RequestMethod.POST)
public ResponseEntity<Object> returnObject(@RequestBody String option)
{
    Object object = wrapperFunction(fetchObjectFromBackend(option));

    return new ResponseEntity<>(object, HttpStatus.OK);
}

The 'wrapperFunction()' mentioned above converts all strings inside the object using EscapeJS()

Lastly, here is an example of an AJAX call:

$.ajax({
        type: "POST",
        headers:
        {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        url: '/urlToController',
        data: option,
        success: function(returnedObject)
        {
            console.log(returnedObject);
        },
        error : function(dataString)
        {
            alert("AJAX Call failed");
            console.log(dataString);
        }
    });

Answer №1

To enhance the string escaping process, there are multiple approaches you can take. One effective method is to develop a custom ObjectMapper that allows you to manage various types of escaping and configurations according to your requirements. By registering this customized ObjectMapper with Spring, you gain complete control over the json generation process. For an example related to Spring MVC, refer to the following link:

For Spring Boot, the process is relatively simpler: Configuring ObjectMapper in Spring

Alternatively, a less complex option involves creating a wrapper object that specifically handles string escaping as part of the bean itself. This means modifying the code snippet from:

Object object = wrapperFunction(fetchObjectFromBackend(option));
return new ResponseEntity<>(object, HttpStatus.OK);

To something similar to below:

Object object = wrapperFunction(fetchObjectFromBackend(option));
//The wrapper would perform the necessary escape calls and offer a single property 
//to deliver the escaped string
MyWrapper wrapped = new MyWrapper(object);
return new ResponseEntity<>(wrapped, HttpStatus.OK);

In the constructor of MyWrapper, you can outline the required data manipulation. Alternatively, you have the choice to directly return the escaped string if preferred:

return new ResponseEntity<>(wrapped.getEscapedString(), HttpStatus.OK);

While using the ObjectMapper might be more sustainable in the long run, the approach you choose should align with your system's needs and future plans.

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

What is the best way to check if an object exists in an array in JavaScript and update it if it does, otherwise add it as a new object in

I am working with an array of objects const target = [{name: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="89fafbe2c9eee4e8e0e5a7eae6e4">[email protected]</a>', selected: false, alertType: 'max&ap ...

Utilizing Squelize's junction table for forming new connections: a comprehensive guide

I am currently working with three basic tables: A, B, and C. The relationship between A and B is many-to-many, so I am using a junction table called A_B. Table C has a one-to-many relationship with the junction table A_B. In sequelize, this is how they are ...

Ways to modify the appearance of the button within ion-calendar

Looking to customize the styling of ion-calendar classes Attempting to add styles to the ion-calendar-month class, but not seeing any changes take effect. ...

Scheduling a cron job to run at a particular date and time

Our express js application includes a feature in the admin module where users can send emails at specific dates and times they select. For example, if the chosen date and time is [email protected], we need to execute the email code at that exact time ...

Issues with javascript and php carousel functionality not performing correctly

I am currently in the process of creating a slideshow/carousel for a website. Recently, I implemented a PHP for-loop to iterate through a folder of images, allowing me to use the slideshow with an unspecified number of images. However, after making this ch ...

Is the format always JSON when querying from the stage?

When working with Snowflake, it's important to note that it supports various file types through the creation of FILE_FORMAT (such as avro, json, csv, etc). I recently conducted tests by SELECTing from the Snowflake stage (s3) for both: *.avro files ...

Step-by-Step Guide: Saving a List of Items in Rows in a Session and Showing it on a Template in Django

Can anyone help with my situation as I am still learning Django Python? I am working on a shopping cart application where Ajax receives the cart items and sends them via POST to a view in Django. In the Django view: def add_product (request): if ...

Retrieve the Country Code and Display a Variety of Greetings

I am new to coding and I am working on creating a customized welcome message for my blog that displays different greetings based on the visitor's country. Currently, I have implemented the following code and it is working perfectly. <script src="h ...

Resolving Logic Errors in PostMapping

My service contains a method that is able to save a fruit in all the stores it has. This method functions properly in the main method, but encounters issues when used with Postman. Upon testing with Postman, only one instance of the fruit is created instea ...

"Mastering the Geocoder Class: Unleashing the Power of AJAX for Latitude and Longitude Retrie

This JSON array includes a collection of addresses [ { "id": 0, "title": "Coop.Sociale Prassi e Ricerca Onlus", "latitude": 0, "longitude": 0, "address": "Viale Eleonora D'Arborea 12, Roma, IT" }, { "id": 0, "title": "San Lorenzo", "lati ...

The connected callback does not trigger when custom HTML elements are being created

Attempting to craft a custom HTML tag using JavaScript, I aimed to create the custom element with ES6 JavaScript syntax. The code devised for this task reads as follows: customElements.define('neo-element', NeoElement); function NeoElement (){ ...

Angular is not programmed to automatically reflect updates made to my string array

let signalRServerEndPoint = 'https://localhost:44338'; this.connection = $.hubConnection(signalRServerEndPoint); this.proxy = this.connection.createHubProxy('MessagesHub'); this.proxy.on("ReceiveMessage", (message) => { ...

How can we use JavaScript to create visual representations of data pulled from a JSON file?

I am interested in utilizing a library similar to the Google Visualization API for creating charts, but with the ability to retrieve data as JSON from an external source. Specifically, I intend to use an SPARQL service to extract information from an XHTML+ ...

Issue with jQuery 'on' event not triggering following 'load' event

I am facing an issue on a page where similar events occur but when new content is loaded halfway through, most of the jQuery functionalities stop working. The scenario involves answering questions in a 'game' format using AJAX calls. Once all que ...

The autoIncrement feature is causing a syntax error at or near "SERIAL"

Encountering a build error : Unable to start server due to the following SequelizeDatabaseError: syntax error at or near "SERIAL" This issue arises only when using the autoIncrement=true parameter for the primary key. 'use strict'; export ...

What is the way to bypass certificate validation when making a Fetch API request in the browser?

The code snippet below is currently being executed in the browser: const response = await fetch(`${url}`, { method: 'POST', headers: { Authorization: `Basic ${authorization}`, }, body: loginData, }) Upon calling this co ...

Resizing a scrollable list using React Refs and UseLayoutEffect

Essentially, my issue stems from having a scrollable list with a set maximum height of '100vh'. I also have a detail card beside the list that contains accordion components. When one of these accordions is expanded, it increases the height of the ...

Send a React component to another component as a prop

I am looking to pass the entire parent component as props to its child component. However, when attempting to pass data from parent to child, I ended up importing the child into the parent. Is there another way to achieve this? Any suggestions on how I c ...

Issues arising from API integration in Django app

Encountering difficulties while making a straightforward API call in a Django application. Take a look at the ajax call below: $.ajax({ type: "GET", url: "/query/", success: function (data) { alert(data); } }); Here is the functi ...

When it comes to adjusting the height of an element, there are two ways to go about it: using $(element).height

function adjustHeight(){ var headerHeight=$(element).find('.header').outerHeight(); console.log(headerHeight); var temp=$(window).height()-headerHeight; console.log(temp); $('.users ...