Search code examples
ajaxspring-bootthymeleaf

Spring boot ajax error with resolving template


My index.html

<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    (js and css)
</head>
<body>
    <div>
        <button name="sendPaperByMessage" th:if="${paper.issend} ne 'sended'" th:paperId="${paper.paperid}">sendMessage</button>
    </div>
    <script th:inline="javascript">
         $("button[name='sendPaperByMessage']").click(function () {
            var paperId = $(this).attr("paperId");
            $.ajax({
                  url: "/api/sendMessage",
                  type: "post",
                  data: {"paperId": paperId},
                  success: function (data) {
                        console.log("success");
                  }
            })
      });
    </script>
</body>
</html>

and my controller:

@PostMapping("/api/sendMessage")
    public Object sendMessage(@RequestParam("paperId") String paperId){
//         paperService.sendMessage(paperId);
         Map map = new HashMap();
         map.put("Message", "success");
         return map;
    }

I omitted some code and make a demo. the response is Error resolving template [api/sendMessage], template might not exist or might not be accessible by any of the configured Template Resolvers"


Solution

  • By default a Controllers returned value is resolved by spring.

    In order to prevent this and return your object as json use @ResponseBody above your method or use RestController instead of Controller. But note that in rest controllers every response is considered not to be a template and thus is not resolved.