您不能在指令內使用'out'變量(或任何其他「預先聲明的」scriptlet變量)。
JSP頁面被您的網絡服務器翻譯成Java servlet。例如,在tomcat中,腳本中的所有內容(開始「<%」)以及所有靜態HTML都被轉換爲一種巨大的Java方法,它將您的頁面逐行寫入到稱爲「out」的JspWriter實例。這就是爲什麼你可以直接在scriptlet中使用「out」參數的原因。另一方面,指令(以「<%!」開始)被翻譯爲獨立的Java方法。
舉個例子,一個非常簡單的頁面(我們稱之爲foo.jsp):
<html>
<head/>
<body>
<%!
String someOutput() {
return "Some output";
}
%>
<% someOutput(); %>
</body>
</html>
最終會看起來像這樣(有很多細節的忽略清晰度):
public final class foo_jsp
{
// This is where the request comes in
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
// JspWriter instance is gotten from a factory
// This is why you can use 'out' directly in scriptlets
JspWriter out = ...;
// Snip
out.write("<html>");
out.write("<head/>");
out.write("<body>");
out.write(someOutput()); // i.e. write the results of the method call
out.write("</body>");
out.write("</html>");
}
// Directive gets translated as separate method - note
// there is no 'out' variable declared in scope
private String someOutput()
{
return "Some output";
}
}
謝謝你的不錯的答案,但它不是我要找的。 – ansgri 2008-09-26 16:48:32
除非使用表達式語法<%= %>,否則對someOutput的調用將不會放入out.write語句中。當您使用scriptlet語法時,它只是內嵌插入。 – 2008-09-26 17:00:21