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

javascript issue with showing content on click

I'm currently working on a school assignment where I am using the onclick() function to display information about an object. However, I am facing an issue where the information is not popping up as expected. HTML <!DOCTYPE html> <html> ...

What is the most effective method for sorting through vast amounts of data with Javascript, React, and Redux?

Currently, I am working with a minimum JSON data set of 90k [...] and utilizing the .filter method. Everything is functioning correctly without any issues, however, from a performance standpoint, I am curious about potential improvements. Any suggestions o ...

Using DART language to read a JSON file stored locally on the client side, eliminating the need for a server

Having some trouble reading data from a JSON file with the following code: void fetchData(Event e){ var path='json/data.json'; var request= new HttpRequest(); request ..open('GET', path) ..onLoadEnd.liste ...

Securing and unscrambling the json file in a node.js environment

Is there a way to encrypt and decrypt a JSON file in node.js? I attempted to run this program and encountered an error stating that File password tty.setrawmode is not a function. Original text: { "production" : { "db" : { "database" : "my ...

Easily update the title of a webpage in the browser's history using JavaScript

Is it feasible to use JavaScript to modify the title of a page in the browser history even after the page has finished loading? This functionality should work consistently across different browsers, including those that do not support the HTML5 History API ...

Default value for the href property in NextJS Link is provided

Is there a default href value for Next/Link that can be used, similar to the way it is done in plain HTML like this: <a href='#' ></a> I attempted to do this with Link, but it resulted in the page reloading. Leaving it empty caused a ...

Setting a default value for Autocomplete in MaterialUI and React.js

Is there a way to set a default value for an Autocomplete TextField component from Material UI in React.js? I want to load a pre-populated value from the user's profile that can then be changed by selecting another option from a list. Check out my co ...

Encountered a runtime error in NgRx 7.4.0: "Uncaught TypeError: ctor is not a

I'm facing difficulties trying to figure out why I can't register my effects with NgRx version 7.4.0. Despite simplifying my effects class in search of a solution, I keep encountering the following error: main.79a79285b0ad5f8b4e8a.js:33529 Uncau ...

What could be the reason for XMLHttpRequest's readystate being something other than 4?

Currently delving into the realm of AJAX for the first time, and endeavoring to construct a basic application that computes the required grade on a final exam based on past assessment results. The user keys in their grades into the form, subsequent to whi ...

Simple steps to turn off error highlighting for TypeScript code in Visual Studio Code

Hey there! I've encountered an issue with vscode where it highlights valid code in red when using the union operator '??' or optional chaining '?.'. The code still builds without errors, but vscode displays a hover error message st ...

``The Vue.js routing system is determined by the incoming data received

Working with VueRouter to navigate to a component based on payload. { path: '/foobar', name: 'foobar', component: foobar, } { path: '/foobar', name: 'foobarSuccess', component: foobarSuccess, query: { ...

Tips on customizing the color of checkboxes in a ReactJS material table

I'm working on a project that involves using the Material table, and I need to change the color of the checkbox when it's selected. Can anyone help me with this? https://i.stack.imgur.com/JqVOU.png function BasicSelection() { return ( <M ...

Reduce the noise from different versions by utilizing package-lock.json

There may not be a clear-cut answer, but I'm curious to hear how others handle the issue of package-lock.json causing problems when committing to their node repository. Many opinions lean towards committing package-lock.json - ensuring consistent dep ...

Checking if the iframe location has been modified using Jquery

Looking to determine if the location of an iframe has been modified. function checkLocation() { setInterval(function(){alert("Hello")},3000); if (document.getElementById("myiframe").src = 'http://www.constant-creative.com/login';) { } ...

Attempting to organize date and time down to the second

I'm currently working on sorting time with seconds included. While I am able to sort the minutes successfully, I'm facing difficulty in sorting the seconds. Despite trying various approaches and using dynamic data that needs to be sorted in desce ...

Combining JSON Files within an AngularJS Service

I utilize a Service in my angular application to retrieve JSON data pertaining to a football team. angular.module('UsersApp').factory('SquadService', ['$http', function($http) { return $http.get('squad/squad-bourne ...

Ajax request experiencing 500 Internal Server Error. Uncertain about the source of the issue

I'm encountering a 500 Internal Server Error and I'm struggling to pinpoint the root cause of the issue. The purpose of this request is to delete a comment with a specific id from the database. The id is passed through a hidden input field. Below ...

Retrieving HTML array values using jQuery

Presented below is an array of input boxes. <form> 9 <input type="checkbox" name="date[]" value="9"> 10 <input type="checkbox" name="date[]" value="10"> 11 <input type="checkbox" name="date[]" value="11"> </form> The o ...

Ways to export redux store data to an external JSON file?

My Redux store is structured as object key value pairs listed below: { "appElements": { "layers": { "layer_1": { "scene": { "width": "100px", "height": "100px", "bgColor": "#aaaaaa", "bgImage": " ...

Adjusting the font color when hovering over multiline text

I am currently in the process of coding a website for my job, and I am working on changing the text color when it is hovered over. However, there seems to be a break in my code causing the text not to highlight all at once. Any guidance or suggestions on h ...