我需要programmaticaly渲染的JSP頁面。
究竟是什麼功能要求?你顯然在找錯方向的解決方案。它是什麼,你認爲這是解決方案的問題/要求?我們可能會提出更好的建議。
例如,您是否需要其輸出?如果是這樣,那麼java.net.URLConnection
就足夠了。
編輯:您編輯您的問題:
我想在編譯之前修改源JSP以某種方式(合併兩個JSP在一起,要準確),所以我需要一種方法來編譯JSP結果從InputStream(或Reader)直接使用JSP Compiller。
OK,這是一個位更加清晰。但是,你需要這個嗎?這些JSP實際上代表什麼?應該使用的最終結果是什麼?
例如,您是否想要在其他JSP中包含一個JSP?例如。包括一個head.jsp
在main.jsp
?如果是這樣,那麼<jsp:include>
就足夠了。或者更糟糕的是,它們是否包含原始Java代碼和一些您想要重用的特定代碼?如果是這樣,那麼你應該使用普通的Java類,如果必要的話使用taglibs。
編輯2:當你說:
但現在我們需要一種方式來使用這些JSP頁面(這是儲存在內存中的方式)作爲佈局的所有JSP頁面用戶請
只存儲web應用程序的web內容的內部磁盤文件系統上的JSP文件(ServletContext#getRealPath()
可能會進入救援在這裏),並轉發給自己的主JSP文件的請求使用的考試,其中包括兩個JSP文件PLE:
<jsp:include page="${page1}" />
<jsp:include page="${page2}" />
編輯3:我創建了一個SSCCE證明其工作。
package mypackage;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TestServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
File root = new File(getServletContext().getRealPath("/"));
String main = "<jsp:include page=\"${page1}\" /><jsp:include page=\"${page2}\" />";
write(main, new File(root, "main.jsp"));
String page1 = "<p>We are in ${data1}";
write(page1, new File(root, "page1.jsp"));
request.setAttribute("page1", "page1.jsp");
request.setAttribute("data1", "first jsp");
String page2 = "<p>We are in ${data2}";
write(page2, new File(root, "page2.jsp"));
request.setAttribute("page2", "page2.jsp");
request.setAttribute("data2", "second jsp");
request.getRequestDispatcher("main.jsp").forward(request, response);
}
private static void write(String content, File file) throws IOException {
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
writer.write(content);
} finally {
if (writer != null) try { writer.close(); } catch (IOException ignore) {}
}
}
}
在http://localhost:8080/playground/test(或者你使用任何主機/ CONTEXTNAME)執行它,你會看到
We are in first jsp
We are in second jsp
爲了更高效的I能緩存一切資源和利用File#exists()
到檢查特定頁面是否已經保存在磁盤上。
我有一個類似的問題,我發現「最簡單」的解決方案是將整個項目切換到Velocity(或其他模板引擎),在這些任務是微不足道的。看起來你在開發過程中已經太過於做出這樣的改變,但只是說... – serg 2009-11-12 02:25:33