skip to Main Content

I have a java Map<Country, List<Expr>> countryToExprMap in the backend service.
In my web page rendered by Thymeleaf, I have a Country drop down to select Country, and a Expr drop down, where I only want Exprs mapped by the selected Country to be displayed.
To do that, I need to pass countryToExprMap from Java to Javascript so that I can know the eligible Exprs from a given Country, so as to build a updateExprOptions function to be called by the Country dropdown on "change" event. Something like:

var exprDropDown = document.getElementById("exprs");

// Map from Java
var exprs = countryToExprMap[selectedCountry];

// Create options for the expr dropdown
for (var i = 0; i < exprs.length; i++) {
    var option = document.createElement("option");
    option.value = exprs[i];
    option.text = exprs[i];
    exprDropDown.appendChild(option);
}

Unfortunately it doesn’t look like there’s a way to pass the map variable from Java to JavaScript. Any advice appreciated.


What I can think of is to stringify the map in Java,
set it as data-* attribute to a html element using Thymeleaf,
and at last deserialise the map in JavaScript to use it there.

2

Answers


  1. Chosen as BEST ANSWER

    Thanks to @Metroids.

    I was able to use Thymeleaf native way to solve it:

    
    // Access public static final Map COUNTRY_TO_EXPR_MAP in MyUtil.java
    <script th:inline="javascript"
            th:with="countryToExprMap=${@my.package.MyUtil@COUNTRY_TO_EXPR_MAP}">
        const exprsMap = new Map(Object.entries([[${countryToExprMap}]]));
        ...
    </script>
    
    

  2. Something like this (change ObjectMapper to any JSON stringifier you have)

      ObjectMapper mapper = new ObjectMapper();
      String jsonStr = mapper.writeValueAsString(countryToExprMap);
    %>
    
    <script>
    const exprs = JSON.parse('<%=jsonStr%>');
    document.getElementById("exprs")
      .innerHTML = `<option value="">Please select</option>
        ${exprs.map(val => `<option value="${val}">${val}</option>`).join("")}`;
    </script>
    

    If the JSON is not in the JSP, but can be delivered by your backend ass a file, then it is simpler:

    fetch("yourListServiceReturningJSON")
    .then(response => response.json())
    .then(exprs => {
      document.getElementById("exprs")
        .innerHTML = `<option value="">Please select</option>
        ${exprs.map(val => `<option value="${val}">${val}</option>`).join("")}`;
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search