1

What is the best way to access a java Map from javascript while using Spring MVC?

I'm building a webpage where depending on the values you chose from a checkbox, a dynamic text will appear in another div with further details regarding that option by using getElementById("element").innerHTML=${var}.

I'm using Maps to populate the checkbox options, and it does works fine in JSPs but simply won't work in javascript scriptlets or external .js files. It just understands it as a string, not as a Map or Array.

The following code is what I've got so far:

Properties file:

checkBoxItems={'0':'The Value'}
myMapObject={'0','Map Stuff'}

In Controller java file:

@Controller
@RequestMapping(value = "/example")
public Class ExampleController
{

     @Value("#{${checkBoxItems}}")
     Map<String, String> checkBoxOptions;

     @Value("#{${myMapObject}}")
     Map<String, String> myMapObject;

     @RequestMapping(value = "/newExample", method = RequestMethod.GET)
     public String Hello(Model model)
     {
     model.addAttribute("checkBoxOptions", checkBoxOptions);
     model.addAttribute("myMapObject", myMapObject);

     return "view";

     }
}

in JSP: (I've simplified to show what I aim to achieve)

<form:select class="custom-select" id="metodologia" path="metodologia"
      onchange="FillWithComplement('${myMapObject}')">

    <form:option value="-">Select an Option</form:option>
    <form:options items="${checkboxOptions}"/>

</form:select>

In the first javascript trial:

<script>

     function FillWithComplement(MapObject) 
     {

     document.getElementById("div").innerHTML = MapObject;
     }

</script>

the output is:

 {0=Map Stuff}

And it also doesn't work if I do:

<script>

     function FillWithComplement(MapObject) 
     {

     var newMap = new Map(MapObject);
     document.getElementById("div").innerHTML = newMap;
     }

</script>

And I am aware I might not have enough javascript knowledge do handle this correcty. Thanks.

EDIT:

As proposed by Yan Khonski, passing data as JSON by asynchronous request (ajax) worked with minor changes.

  • dataType: 'json' returns a JSON object, so it is needless to implement a JSON parsing method.

The final code:

 var globalMetodologiaComplemento;

 $(document).ready(function () {
     $.ajax({
         type: 'GET',
         url: '/gla/getMet',
         dataType: 'json',
         success: function (data) {

             globalMetodologiaComplemento = data;
             console.log(globalMetodologiaComplemento[0]);
         }
     });
 });
 (...)
  • Alternative https://www.oracle.com/technical-resources/articles/javase/servlets-jsp.html You can access map values as attributes (object fields) – Yan Khonski May 12 '20 at 22:42

1 Answers1

0

You can have a REST end-point which returns data in JSON format. Then your client - javascript code, will make an asynchronous request (after the page has loaded) to the rest end-point and get the data. Then js code will parse JSON into object and can work with it.

1) Controller returns model and view. The view is a JSP page.

@Controller
@RequestMapping(value = "/example")
public Class ExampleController
{

     @Value("#{${checkBoxItems}}")
     Map<String, String> checkBoxOptions;

     @Value("#{${myMapObject}}")
     Map<String, String> myMapObject;

     @RequestMapping(value = "/newExample", method = RequestMethod.GET)
     public String Hello(Model model) {
         model.addAttribute("checkBoxOptions", checkBoxOptions);
         model.addAttribute("myMapObject", myMapObject);

         return "view";
     }

    @ResponseBody
    @GetMapping("/additional-data")
    public String getData() {
        return objectMapper.writeValueAsString(yourObject);
    }
}

Check Jackson library to serialize objects into JSON.

2) Once jsp page is loaded, you can make an asynchronous (AJAX) request to another end-point in your controller. This endpoint will return JSON data (you will have to serialize your object into JSON). https://api.jquery.com/jquery.ajax/

How to parse JSON data with jQuery / JavaScript?

https://stackoverflow.com/a/32593283/1839360

$(document).ready(function(){
$.ajax({
  type: 'GET',
  url: 'http:localhost:8080/example/additional-data',
  dataType: 'json',
  success: function (data) {
    //data downloaded so we call parseJSON function 
    //and pass downloaded data
    var object = $.parseJSON(data); // use browser debugger to see that properties the object has
  }
});
});

3) Your client JS code will receive a response from AJAX call and parse the data.

Yan Khonski
  • 12,225
  • 15
  • 76
  • 114
  • I gave you a concept how to do so. Note, my code may contain mistakes, but I provided you links which give you a direction to go. – Yan Khonski May 12 '20 at 22:40
  • 1
    Thank you. It worked with minor changes. I've edited my original post so it may be helpful to others. Check it out if you wish to see how the problem has been actually solved. – Raphael Heizer May 13 '20 at 18:34
  • @Heizr, you can edit my answer, if you see an improvement. I'm glad that it worked for you. – Yan Khonski May 13 '20 at 19:38