如何使用JSP include或c:import或symlink加载应用程序上下文之外的Html页面

Gan*_*h K 2 jquery jsp jstl jsp-tags jspinclude

我需要使用jsp include标签将一些其他应用程序动态创建的html页面加载到我的应用程序jsp页面中<jsp:include page="${Htmlpath}" /> OR <jsp:include page="D:\MySharedHTML\test.html" />.我的想法是在服务器上有一个共享文件夹,如"MySharedHTML",让其他应用程序在那里创建html文件,我的应用程序将通过提供完整路径访问.但jsp include表示"请求的资源D:\ MySharedHTML\test.html不可用".任何输入如何做到这一点.提前致谢.

Bal*_*usC 5

必须通过URL提供.该D:\MySharedHTML\test.html是很绝对不是一个有效的URL.有效的URL看起来像这样http://localhost:8080/MySharedHTML/test.html.

是使用<jsp:include>还是<c:import>取决于URL是内部URL还是外部URL.在<jsp:include>只对内部URL作品(因此,在相同的Web应用程序的资源,也是那些私自隐藏/WEB-INF).该<c:import>作品此外还对外部URL(因此,在一个完全不同的web应用程序的资源,但这些都必须公开访问;即你有看到希望的包括内容已经copypasting在浏览器的地址栏中的URL时).

在您的特定情况下,您似乎将它放在服务器的本地磁盘文件系统的其他位置,而真正的URL根本无法使用它.在这种情况下,你基本上有两种选择:

  1. 将该路径的根文件夹作为虚拟主机添加到服务器配置中.如何做到这一点取决于您没有说明的服务器make/version.以Tomcat为例,这将是添加以下条目的问题/conf/server.xml:

    <Context docBase="D:\MySharedHTML" path="/MySharedHTML" />
    
    Run Code Online (Sandbox Code Playgroud)

    这样,所有文件夹的内容都可用http://localhost:8080/MySharedHTML/*,包括test.html.这样你可以使用<c:import>它(注意:<jsp:include>不适用,因为它不在同一个webapp中).

    <c:import url="/MySharedHTML/test.html" />
    
    Run Code Online (Sandbox Code Playgroud)
  2. 创建一个servlet,它充当本地磁盘文件系统的代理.假设您正在使用Servlet 3.0/Java 7,并且您可以${Htmlpath}以仅返回的方式更改变量test.html,那么这应该:

    @WebServlet("/MySharedHTML/*")
    public class PdfServlet extends HttpServlet {
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String filename = request.getPathInfo().substring(1);
            File file = new File("D:\\MySharedHTML", filename);
            response.setHeader("Content-Type", getServletContext().getMimeType(filename));
            response.setHeader("Content-Length", String.valueOf(file.length()));
            response.setHeader("Content-Disposition", "inline; filename=\"" + URLEncoder.encode(filename, "UTF-8") + "\"");
            Files.copy(file.toPath(), response.getOutputStream());
        }
    
    }
    
    Run Code Online (Sandbox Code Playgroud)

    (当不使用Servlet 3.0/Java 7时,只需回到明显的web.xml注册和InputStream/OutputStream loop样板)

    由于servlet在同一个webapp中运行,<jsp:include>应该可以正常工作:

    <jsp:include page="/MySharedHTML/${HtmlFilename}" />
    
    Run Code Online (Sandbox Code Playgroud)