Tips for transferring a Spring MVC controller variable to JavaScript

I am currently working on retrieving a variable for a JavaScript function from an object that is sent to the view by the controller.

The object I am dealing with is called Bpmsn.

https://i.sstatic.net/FxlAo.png

Through the controller, I have injected the object into the view.

This is the method in the controller:

@RequestMapping(value = "/display")
public ModelAndView index2(@RequestParam int bpmsnId) {
    ModelAndView result;
    Bpmsn bpmsn;

    bpmsn = bpmsnService.findOne(bpmsnId);

    result = new ModelAndView("editor/display");
    result.addObject("bpmsn", bpmsn);

    return result;
}

This method is used to display the object.

In the JSP view, I inject the attributes of the object, except for the textXML attribute which will be used in a JavaScript script.

<div>
<ul>
    <li><b><spring:message code="bpmsn.ticker" />:</b> <jstl:out
            value="${bpmsn.ticker}" /></li>
    <li><b><spring:message code="bpmsn.title" />:</b> <jstl:out
            value="${bpmsn.title}" /></li>
    <li><b><spring:message code="bpmsn.summary" />:</b> <jstl:out
            value="${bpmsn.summary}" /></li>
    <li><b><spring:message code="bpmsn.authoredMoment" />:</b> <jstl:out
            value="${bpmsn.authoredMoment}" /></li>
    <li><b><spring:message code="bpmsn.likes" />:</b> <jstl:out
            value="${bpmsn.likes}" /></li>
    <li><b><spring:message code="bpmsn.dislikes" />:</b> <jstl:out
            value="${bpmsn.dislikes}" /></li>
</ul>

For the textXML attribute, I intend to create a JavaScript function to import that XML into a BPMN modeler. However, I am unsure of how to retrieve the textXML attribute of the injected object in the view from the JavaScript script.

I attempted to call the attribute as done in the view but it was unsuccessful

<script type="text/javascript">
var bpmnXML = ${bpmsn.textXML}; //not work
alert(bpmnXML)
// BpmnJS is the BPMN viewer instance
var viewer = new BpmnJS({
    container : '#canvas'
});

// import a BPMN 2.0 diagram
viewer.importXML(bpmnXML, function(err) {
    if (err) {
        // import failed :-(
        alert('could not import BPMN 2.0 diagram', err);
    } else {
        // success!
        var canvas = viewer.get('canvas');
        canvas.zoom('fit-viewport');
    }
});

Answer №1

One way to send data from Spring MVC to JavaScript is by using the following approach:

 <script>
    var num = [[${num}]];
    var text = "[[${text}]]";
</script>

Answer №2

When dealing with Java objects stored in the model, it can be difficult to access them in client-side scripts.

An easy solution is to serialize the object into JSON format, add it to the model, and then access it in JavaScript.

You can achieve this by using the following code snippet:

ObjectMapper objectMapper = new ObjectMapper();
result.addObject("bpmsn", objectMapper.writeValueAsString(bpmsn));

Once the object is serialized and added to the model, you can easily access it in your script like so:

var bpmnJsonString = '${bpmsn}';
Obj bpmn = JSON.parse(bpmnJsonString);
var bpmnXML = bpmn.textXML; 
alert(bpmnXML)

I hope this helps resolve any issues you may have encountered.

Answer №3

The reason this code is not functioning correctly is because the line var bpmnXML = ${bpmsn.textXML}; is being executed solely on the client side.

An alternative approach would be to incorporate a hidden field with an attribute containing the value ${bpmsn.textXML}, which will then be processed on the server side. By doing so, you can access this value in your JavaScript code (I prefer using jQuery for demonstration purposes).
For instance:

<input id="bpmsn-textxml" type="hidden" data-textxml="${bpmsn.textXML}"/>

var bpmnXML = $("#bpmsn-textxml").data("textxml");

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 process for updating a placeholder text after the user makes a guess or enters

My latest project involves creating a fun guessing game where players have to identify the driver based on the teams they have driven for. The game displays the number of guesses allowed and keeps track of how many attempts the player has made so far. For ...

Implementing initial state checks for Alpine.js checkboxes based on x-modal is not functioning properly

Upon loading alpinejs, for some reason all checkboxes become unchecked. It's perplexing and I can't figure out why. <div x-data="{ colors: [orange] }"> <input type="checkbox" value="red" x-model="co ...

What is the best way to retrieve a specific object from a JSON file using a Get request in a Node.js application?

My focus is on optimizing an API, which is why I'm working with only the data that's essential for my analysis. I've set up a route to extract specific objects, but I'm only interested in four of them: account_manager, fronter, closer, ...

What are the benefits of incorporating 'i in array' into my personalized 'array.indexOf' function?

I've come across code like this multiple times: function customArrayIndexOf(item, array){ for (var i = 0, l = array.length; i < l; i++) { if (i in array && array[i] === item) return i; } return -1; } But I'm unsur ...

Create a pop-up window within a single controller using Angular.js

I followed a tutorial to create this code. I am interested in learning how to utilize just one controller for generating the dialog box. Currently, I am using two controllers for this project. Any guidance or tips would be greatly appreciated. View my cod ...

Fetching Data Using Asynchronous API Calls

My goal is to retrieve all results consistently from the API, but I am encountering varying outcomes. The for loop seems to be skipping some requests and returning a random number of records. Can anyone provide assistance? I have experimented with using t ...

What is the best method for displaying a radio button as selected based on a variable value?

I have a variable that stores the value of a radio button. After checking certain conditions, I want to dynamically select the radio button based on this value. if(cheque_date == system_date) { cheque_value='Current'; } else { cheque_value ...

Double-clicking with Ajax and JSF after the initial click

When I interact with a dataTable that has a column named DELETE (which is a link) and has a listener attached to it, I experience an issue. After clicking on the link for the first time (click 1), the row gets deleted as expected. However, subsequent click ...

What is the best way to utilize JSON data stored in a Jekyll _data folder?

As per the documentation on Jekyll, it is mentioned that you can access YAML, JSON, and CSV files located in the `_data` directory using `{{ site.data.filename }}`. I have a geoJson file named `chapters.json` which consists of point features. While I am a ...

How do you modify the SVG viewport using code?

I am looking to create a feature that allows all images inside an SVG object to be moved. My plan is to use JavaScript, and possibly jQuery, to handle mouse events (down, move, up) in order to change the viewport of the SVG. However, I am currently facing ...

Unable to replicate the exact Bootstrap template found on their website

Attempting to replicate a template from bootstrap.com, but encountering issues with the copied version. The navigation bar is turning white instead of remaining black, and I'm unable to change the color. Additionally, facing problems with the toggle ...

Using jQuery to Check Cookies and Hide Content Depending on the Value and Data Attributes

On a webpage, I have a collection of coupons with unique data attributes (data-coupon). Currently, I am using cookies to store the value associated with each coupon (ranging from 1 to 4). While my code is functional, it feels repetitive and cumbersome. S ...

jQuery.get() function is limited to specific types of webpages

I have successfully combined multiple weather APIs on my website, which can be found here. Recently, I started using the weather.gov API and it has been quite effective. However, there are certain data points that I need to extract which the weather.gov A ...

Command field in Javascript

I've crafted an exquisite search box for my website, but I'm struggling to make it functional and display search results. Below are the Html and CSS files pertaining to this section of my site: .searchbox{ /*setting width of the form eleme ...

Pattern Update Method: Iteratively updating each individual node

I'm struggling to grasp the concept of updating only those d3 nodes where the data has changed. Despite my efforts, I still can't seem to get it right. In the test example provided below, I am noticing that everything is being updated instead of ...

Deleting uploaded images in Cloudinary for Next.js is not allowed

After successfully implementing image uploads in cloudinary for Next.js, I encountered an issue with image deletion. Despite creating the necessary routes and components, the deletion functionality is not working as expected. I am unsure of what could be ...

Can webpack effectively operate in both the frontend and backend environments?

According to the information provided on their website, packaging is defined as: webpack serves as a module bundler with its main purpose being to bundle JavaScript files for usage in a browser. Additionally, it has the ability to transform, bundle, or ...

Efficiently convert a JSON array into an HTML table using the Jquery

Currently, I'm facing a challenge in my project. The issue arises when a query is sent to the server using jQuery, and an array is returned as a response. My struggle lies in transferring this data to a dynamic table since the column count varies with ...

Disable setTimeout in Node.js triggered by an event

I am facing a dilemma with my code that constantly polls a service and I am looking for a way to efficiently cancel the interval using `clearTimeout` through events. The timeouts essentially act as intervals by calling setTimeout again within the function. ...

Can anyone recommend a drag-and-drop feature in Javascript that functions seamlessly on both iPad and PC devices?

Can anyone recommend a JavaScript plugin that allows for drag and drop functionality on both touch and mouse enabled devices, including IOS, Android, PC, and Mac? For touch-enabled devices, I found an example here: And for mouse-enabled devices, there is ...