'How to access model attribute in html page in Spring MVC?

I have Spring MVC project where the views are html pages. I am setting model attribute in my Controller method but unable to access it on html view page.

Here is my Controller method.

@RequestMapping(value = "/", method = RequestMethod.GET)
 public ModelAndView getData() {

  ModelAndView model =new ModelAndView();
  model.addObject("name", "Jack");
  model.setViewName("html/firstLayer.html");
  return model;

 }

This is how i am accessing it in my html page

<script type="text/javascript">
    var name1 ='${name}' ;
    console.log(name1);
 </script>

But on console it is printing ${name}, it should print Jack. Any help will be appreciated , Thanks.



Solution 1:[1]

You cannot do that directly through Javascript. You either need to use a JSP file to retrieve the server side ModelAndView variable that you have set.

Or you can go with a better solution.

@RequestMapping(value = "/", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public String getData() throws JsonProcessingException {
    Map<String, Object> myData = new LinkedHashMap<>();
    myData.put("name", "Jacky");
    ObjectMapper objectMapper = new ObjectMapper();
    return objectMapper.writeValueAsString(myData);
}

Basically when you do a get, you will return a string to the client side, then you can take the string from the request via a ajax call and manipulate the data with javascript as you want.

Spoiler: this is a very rough implementation. I would recommend changing the Map into an object, like a separate class MyDataClas with the fields that you want and if you are using spring web, you can add jackson in your classpath and instead of converting your object into string, you can return directly your class (spring will deal with serialization of the object to json):

 @RequestMapping(value = "/", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody MyDataClass getData() {
    final MyDataClass myDataClass = new MyDataClass();
    myDataClass.setName("Jacky");
    return myDataClass;
}

This would look much better than the first and cleaner.

You can look over a few tutorials regarding this to better understand how this works here

Solution 2:[2]

in html we can use model value. so when document is loaded then name will present as hidden field in page. and using javascript or jquery we can access it. Here is an example:

<input type="hidden" id="name" value='${name}'/>

<script type="text/javascript">
    var name"1 = $(#name).val();
    console.log(name1);
 </script>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andrei Sfat
Solution 2 Adam Richardson