Search code examples
springspring-bootspring-mvcthymeleaf

How to get spring MVC controller model key value inside <script> tag


I have looked at duplicate questions but could not relate to my problem. I am new to Spring MVC. My controller code is

@RequestMapping(value = "/employee/add", method = RequestMethod.POST)
public String addNewPost(Employee emp, BindingResult bindingResult, Model   model) {
   empr.save(emp);
   model.addAttribute("Employees", empr.findAll());
   System.out.println(empr.findAll());
   return "display";
}

My javascript code is

<script type="text/javascript">
   var data1 = [];
   $(document).ready(function(){
   var emp = ${Employees};// shows Uncaught SyntaxError: Unexpected token { in this line

I want to get reference to Employees key that is sent through model.addAttribute. How can this be done? It is working fine in html though using thymeleaf. (I am using STS 3.8.1 with jquery-1.11.1.min.js and spring-boot-starter-thymeleaf 1.4.0 Release)

<p th:each="emp : ${Employees}">
<h4>ID:</h4>
<div th:text="${emp.id}"></div>
<h4>Title:</h4>
<div th:text="${emp.name}"></div>
<h4>Content:</h4>
<div th:text="${emp.address}"></div>
<h4>Salary:</h4>
<div th:text="${emp.salary}"></div>
<div>---------------------------------------------------------</div>

</p>

Solution

  • You are using thymeleaf - so you can do this to make it work:

    <script th:inline="javascript">
         /*<![CDATA[*/
         var emp = [[${Employees}]];
        /*]]>*/
    </script>
    

    The CDATA part (note that it is commented too) tells thymeleaf to ignore this section while doing its xml-validation.

    And wrapping up the ${Employees} allows you to write this inside a script tag.