Search code examples
jqueryajaxspringdrop-down-menuthymeleaf

Dynamic Drop down menu using Thymealeaf and database throw exception


I am trying to do a dynamic drop down menu. First I have to select from a menu an IDE, and then according to my choice Versions of this IDE should appear.

1.First Drop down menu

<select class="field-title" id="ide1" name="ide1" th:field="*{ide}"  >
                <option th:each="ideSelected : ${ides}"
                        th:value="${ideSelected.getIDEName()}"
                        th:text="${ideSelected.getIDEName()}"></option>
            </select>
  1. Second Drop down menu
<select class="field-title" id="versionContent" name="versionContent" th:field="*{versions}" >          </select>
  1. Script
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
        $(document).ready(function() {
            $("#ide1").change(function() {
                sendAjaxRequest();
            });
        });
    </script>
    <script>
        function sendAjaxRequest() {
            let ide = $("#ide1").val();
            $.get("/ides/" + ide, function( data ) {
                // $("#versionContent").empty();
                data.forEach(function(item) {
                    let option = "<option value = " + item + ">" + item +  "</option>";
                    $("#versionContent").append(option);
                });
            });
        }
    </script>

  1. Controller
@GetMapping(value = "/{ideName}")
    public Set<String> getAllVersions(@PathVariable("ideName") String ideName){
        IDE ide = ideService.getIdeByName(ideName);
        return ide.getVersions().stream().map(Version::getVersion).collect(Collectors.toSet());
    }
  1. Error thrown
[THYMELEAF][http-nio-8080-exec-2] Exception processing template "ides/IntelliJ": An error happened during template parsing (template: "class path resource [templates/ides/IntelliJ.html]")

org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/ides/IntelliJ.html]")

Could someone give me a hand for this? Thank you!


Solution

  • To have Spring serialize the response of the controller method to JSON, you need to use @RestController, or @ResponseBody on the method itself if you are using @Controller.