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:
I require a function to 'unescape' these strings and restore them to their original form for proper functionality.
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.
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);
}
});