Search code examples
spring-bootspring-mvcthymeleaf

Error in passing models between Spring MVC Controller and Javascript


In a Spring Boot project with Java 1.8 I'm having difficulty in correct communication between the controller which displays the values ​​correctly and the front-end part which doesn't seem to be able to receive them correctly.

I have the following endpoint in the controller:

    @GetMapping(value = {"/test"})
    public String test(Model model) {

        List<String> list = getFieldNamesExcluding(Arrays.asList("title", "type", "link", "referenceDates"));

        model.addAttribute("inputs", list);

        return "test";
    }

The content is a string representing an array of strings (e.g. “[hello,how,are,you]”) The value of which I checked to be correct by debugging.

The html page to which the model is passed is:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Test Page</title>
</head>
<body>
<button type="button" th:text="Press here" onclick="start()"></button>

<script th:inline="javascript">
    function start() {
        /*<![CDATA[*/
            var inputs= /*[[${inputs}]]*/ 'default';
            console.log("inputs: ",inputs);
        /*]]>*/
    }
</script>
</body>
</html>

But that way I get: message: null.

I also tried receiving the value with JSON.parse() and using an hidden input: <input type=“hidden” id=“inputs” th:value=“${inputs}” /> but the result is a blank space.

PS: I'm using the 2.7.18 version of Spring Boot in the pom, to include Thymeleaf,


Solution

  • I created a small test with the html being used and it seems there is an issue with the button tag which causes the thymeleaf processing to fail.

    This th:text="Press here" is not a valid thymeleaf expression.

    Use the following button tag and it should be fine.

    <button type="button" onclick="start()">Press Here</button>