Search code examples
javaspring-bootthymeleaf

Fetch thymeleaf fragments from external URL


I have a spring-boot/thymeleaf website on server A, and I want to load some fragments from server B. The fragments are dynamic and some of them call java methods defined in server A, so what I need is to fetch those fragments (as plain text?) from server B and include them in my html pages in server A, where they will be processed etc. Server B will act like a repository, it won't do any processing at all, just serve the fragments to server A.

Is this possible?


Solution

  • Ok, I posted this question because all my attempts were failing, but after all it was just a typo that was holding me back... So here's what worked for me, in case anyone is interested:

    1. I saved the fragments in src/main/resources/static/fragments on server B. Let's assume a file named frg with a fragment called "content" inside it.

    2. I created a controller in server B to serve the files as plain text, like this:

        import org.springframework.core.io.ClassPathResource;
        import org.springframework.stereotype.Controller;
        import org.springframework.web.bind.annotation.PathVariable;
        import org.springframework.web.bind.annotation.RequestMapping;
        import org.springframework.web.bind.annotation.ResponseBody;
    
        import java.io.File;
        import java.nio.file.Files;
    
        import javax.servlet.http.HttpServletResponse;
    
        @Controller
        public class FragmentsController {
    
            @RequestMapping(value = "/fragments/{fragmentPage}")
            @ResponseBody
            public String GetFragment (@PathVariable String fragmentPage, HttpServletResponse response) throws Exception {
                response.setHeader("Content-Type", "text/plain");
                response.setHeader("success", "no");
                if (fragmentPage == null)
                {
                    System.err.println("Nothing to serve!");
                    return null;
                }
    
                System.out.println("Serving fragment: " + fragmentPage);
                String fileName = "static/fragments/"+fragmentPage;
    
                File resource = new ClassPathResource(fileName).getFile();
                String frg = "";
                try
                {
                    frg= new String(Files.readAllBytes(resource.toPath()));
                    response.setHeader("success", "yes");
                }
                catch (Exception e)
                {
                    frg = "Error loading fragment: " + e.getMessage();
                }
                return frg;
            }
        }
    
    1. From server A, I can now fetch the fragment like this:
    <div th:include="http://<server_b_url:port>/fragments/frg :: content"></div>