ExTincT
ExTincT

Reputation: 29

Accessing java variable from javascript in spring mvc

i am relatively new to spring mvc.what i am trying to do is pass a variable as model attribute and try and access it on page load with javascript on my JSP page. my java code is as follows

   model.addAttribute("leagueCode",leagueCode);
    model.addAttribute("league","new");
    return "redirect:/Dashboard";

and on jsp side i am trying to access it by following

<script type="text/javascript"> function myFunction() { var leagueCode=${leagueCode}; alert(leagueCode); } </script> </head> <body onload="myFunction()">

but i am getting the value as blank. is this the right way i am following or is there any other way this has to be done? please help

Upvotes: 1

Views: 2133

Answers (1)

Juan
Juan

Reputation: 5589

In the JSP page you can set the values as javascript variables by adding a script tag in the <head> with the assignment inside as a json object for example:

<script>
var myServerSideVars = {
    "aServerSideVarName" : "<here you set the value with el/jslt/scriptlet>",
    "anotherServerSideVarName" : "<here you set the value with el/jslt/scriptlet>" 
};
</script>

EDIT I

Example using EL (Expression Language) but the same could be done with scriptlets if you are using that (<% %>):

Lets say in your Servlet you put a Car instance in the request before forwarding to the JSP page.

The car:

public class Car{
    protected String brand;
    protected String year;

    //getters and setters for the two properties.
}

In the Servlet you put it into the request:

Car car = new Car();
car.setBrand("BMW");
car.setYear("2017");
request.setAttribute("carInRequest", car);

In the JSP you set it to a Json Object accessible from javascript. Before closing the body tag I put a simple example of how the var can be accessed from javascript. I haven't run it so it may have some typo or error to correct:

<%@taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>

    <html>
       <head><title>System.out.println</title>
          <script>
              var aCar= {
                     "brand" : "${requestScope.carInRequest.brand}",
                     "year"  : "${requestScope.carInRequest.year}"
              };
          </script>
       </head>

       <body>
          <h2>Brand: <span id="brandPlaceHolder"></span></h2>
          <h2>Year: <span id="yearPlaceHolder"></span></h2>

       </body>
       <script>
           var brandSpan = document.findElementById("brandPlaceHolder");
           brandSpan.html = aCar.brand;
           var yearSpan = document.findElementById("yearPlaceHolder");
           brandSpan.html = aCar.year;
       </script>
    </html>

Upvotes: 1

Related Questions