【问题标题】:How to display an external website containing javascript from jsp?如何显示包含来自 jsp 的 javascript 的外部网站?
【发布时间】:2018-08-21 06:39:41
【问题描述】:

我必须在 jsp 中嵌入一个 HTML 文件。此 HTML 文件是动态的,必须根据用户请求进行下载。我尝试的是在目录中下载html,然后从jsp显示它。

为此,我尝试过的一种方法是这样的:

public void doGet(HttpServletRequest request, HttpServletResponse response)
                      throws ServletException, IOException {
    response.setContentType("text/html;charset=utf-8");
    PrintWriter out = response.getWriter();
    String externalWeb = "external";
    String externalWebValue = request.getParameter(externalWeb);
    _saveUrl(externalWebValue);
    StringBuilder contentBuilder = new StringBuilder();
    try {
         BufferedReader in = new BufferedReader(new FileReader("/pathToExternal/external.html"));
         String str;
         while ((str = in.readLine()) != null) {
             contentBuilder.append(str);
         }
         in.close();
    } catch (IOException e) {
    }
    String content = contentBuilder.toString();
    String page = content;
    request.setAttribute("page", page); 
    request.getRequestDispatcher("/web/external.jsp").forward(request, response);     

    }


private void _saveUrl(String externalWebValue) {      
    try {
        PrintWriter outputFile = new PrintWriter("pathTo/external.html");
        URL url = new URL(externalWebValue);
        URLConnection con = url.openConnection();
        InputStream is =con.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = null;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
            outputFile.println(line);
        }
        outputFile.close(); 
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }        
}

我尝试直接从网页上阅读。但同样的问题,javascripts 不起作用,页面内容没有加载。

但是当我单击下载的 html 时,一切正常,但是当我在 jsp 中导入它时,没有任何效果。我该如何解决这个问题?

试图像这样将它包含在 jsp 中:

<%@ include file="/web/external.html" %>

仍然没有运气。不使用 iframe 的最佳方法是什么? (我打算渲染的网站不支持 iframe)

【问题讨论】:

  • 您是否尝试过使用&lt;script&gt; 块?
  • @killjoy &lt;script&gt; 块是什么?
  • @killjoy 这有什么帮助?那只是js。我需要在我们的jsp中渲染整个网站。不仅是脚本。而且网站是动态的,可以是任何网站。
  • 哦,我以为你说的是​​ JS,而不是 JSP。我的错。

标签: java html jsp servlets


【解决方案1】:

上述问题的解决方案是在jsp中添加这个:

<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>

<html>
   <head>
      <title> Tag Example</title>
   </head>

   <body>
      <c:import var = "data" url = "${page}"/>
      <c:out value = "${data}" escapeXml="false"/>
   </body>
</html>

在 servlet 中添加:

request.setAttribute("page", externalWebValue); 

使用c tag library 并且必须使用escapeXml="false" 才能完成这项工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-03
    • 2012-12-03
    • 2015-03-20
    • 1970-01-01
    • 1970-01-01
    • 2013-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多