Spring MVC 3.2 Thymeleaf Ajax Fragments

前端 未结 3 850
被撕碎了的回忆
被撕碎了的回忆 2020-12-12 12:09

I\'m building application with Spring MVC 3.2 and Thymeleaf templating engine. I\'m a beginner in Thymeleaf.

I have everything working, including Thymeleaf but I was

3条回答
  •  生来不讨喜
    2020-12-12 12:40

    As an alternate version to Sohail's great answer, I want to give a version that using javascript can send the whole th:object to the controller, integrating Thymeleaf in your forms, not having to use @PathVariable which becomes messy or not usable at all when you've forms with many fields.

    For the form (using an example which returns an object which has an id and a name Strings, and feeds a combobox with a Map that has some of those objects as values) we have:

    Name:

    When this form is submited (using a button with type submit for example) the whole document will be replaced. However we can intercept this submit with javascript and do it the ajax-way. To achieve this, we will add an interceptor to our form using a function. First call the function that adds the interceptor right after the form:

    
    

    And the function looks like this (place it in the head of the document or wherever suits your needs):

    
    

    Now whenever the form is submited, this function will trigger, and it will:

    • Prevent the original form submit
    • Make an ajax call using the url defined in the form's th:action
    • Serialize the form data. Your controller will be able to recieve this in an object
    • Replace the part of your html code with the returned fragment

    The replaced part should look like this

    And the controller can recieve the th:object in the form, with it's values filled, like this (Replace Object with your object's type and "object" with a proper name):

    @PostMapping(value = /yourMapping)
    public String ajaxCtrlExample(@ModelAttribute("object") Object object, Model model) {
        return yourFragmentPath;
    }
    

    And that's everything. Call the function that adds the interceptor after every form you need in ajax-version.

提交回复
热议问题