Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

th:replace by POST response view #988

Closed
kelvinchiew opened this issue Jan 11, 2024 · 1 comment
Closed

th:replace by POST response view #988

kelvinchiew opened this issue Jan 11, 2024 · 1 comment

Comments

@kelvinchiew
Copy link

I would suggest to have th:replace support POST response view.

index.xml

  • fragmenr replace by POST response from server.
<div th:replace="@{~/menu}"></div>

menu.xml

  • contain Spring Modal attribute menuList for further process
<div xmlns:th="http://www.thymeleaf.org">
    <script th:inline="javascript">
        $(document).ready(() => {
            var menuList = /*[[${menuList}]]*/ null;
            console.log(menuList);
            if(null != menuList){
                // some logic to populate menu
            }
        })
    </script>
    <div id="menu"></div>
</div>

MenuController.java

  • POST response to set menuList model attribute
@RequestMapping(value = "/menu", method = RequestMethod.POST)
    public String menu(HttpServletRequest httpServletRequest, Model model) {
        logger.debug("menu controller");
        List<Menu> menuList = null;
        Object object = httpServletRequest.getServletContext().getAttribute(SESSION_NAME_MENU);

        if(Objects.nonNull(object)){
            try{
                menuList = (List<Menu>) object;
            } catch (Exception e){}
        }

        if(Objects.isNull(menuList)){
            Menu home = new Menu();
            home.setId(1L);
            home.setTitle("Home");
            home.setUrl("home.html");
            menuList.add(home);

            // ... more menu
        }

        model.addAttribute("menuList", menuList);
        return "layout/menu";
    }
@jmiguelsamper
Copy link
Member

Hello Kelvin,

Thanks for your suggestion. Thymeleaf is a server-side template engine and, as such, its goal is to produce output by composing the server-side resources instead of doing AJAX calls to render the final content.

Compositing pages using AJAX calls is already done by many Javascript frameworks that do their job very well.

On the other hand, please note that using POST requests to get view content is not a good practice and against the HTTP specification at https://datatracker.ietf.org/doc/html/rfc2616
If you want to get view content, you should always do a GET request, POST is reserved for data modification.

Thanks anyway for your suggestions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants