Java 从外部URL获取thymeleaf片段
我在服务器a上有一个spring boot/thymeleaf网站,我想从服务器B加载一些片段。这些片段是动态的,其中一些调用服务器a中定义的java方法,所以我需要的是从服务器B获取这些片段(作为纯文本?),并将它们包含在服务器a的html页面中,服务器B将充当一个存储库,它根本不会做任何处理,只是将片段提供给服务器aJava 从外部URL获取thymeleaf片段,java,spring-boot,thymeleaf,Java,Spring Boot,Thymeleaf,我在服务器a上有一个spring boot/thymeleaf网站,我想从服务器B加载一些片段。这些片段是动态的,其中一些调用服务器a中定义的java方法,所以我需要的是从服务器B获取这些片段(作为纯文本?),并将它们包含在服务器a的html页面中,服务器B将充当一个存储库,它根本不会做任何处理,只是将片段提供给服务器a 这可能吗?好的,我发布这个问题是因为我所有的尝试都失败了,但毕竟这只是一个打字错误,阻碍了我。。。如果有人对我感兴趣的话,以下是对我有效的方法: 我将片段保存在服务器B上的sr
这可能吗?好的,我发布这个问题是因为我所有的尝试都失败了,但毕竟这只是一个打字错误,阻碍了我。。。如果有人对我感兴趣的话,以下是对我有效的方法:
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;
}
}
<div th:include="http://<server_b_url:port>/fragments/frg :: content"></div>