正如您所知,JSP由Java EE容器即時轉換爲servlet。在<% ... %>
塊中,out
是生成的servlet中生成的_jspService
(或類似的)方法中的局部變量。這是一個JspWriter
用於寫入頁面的輸出。
在<%! ... %>
塊,你外生成_jspService
(或類似)的方法,並讓你的靜態導入意味着你out
參考是System.out
,這是不是在頁面輸出應該發送。
如果你想在<%! ... %>
塊來定義你的JSP方法,你必須通過out
放進去:
<%!
private void test(JspWriter out) throws IOException {
out.println("<p>test</p>");
}
%>
關於JSP - > servlet的東西,說我們有這個JSP :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<%
out.println("The current date/time is " + new java.util.Date());
this.test(out, "Hi, Mom!");
%>
<%!
private void test(JspWriter out, String msg) throws java.io.IOException {
out.println(msg);
}
%>
</body>
</html>
注意,它有一個<%...%>
塊和<%! ... %>
塊。
Java EE容器變成有點像以下內容。注意這裏我們test
方法結束了,並在我們的<%...%>
塊中的代碼結束了(我們的原始JSP文/標記一起):
package org.apache.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class test_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private void test(JspWriter out, String msg) throws java.io.IOException {
out.println(msg);
}
/* ...lots of setup stuff omitted... */
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write("<!doctype html>\n");
out.write("<html>\n");
out.write("<head>\n");
out.write("<meta charset=\"utf-8\">\n");
out.write("<title>Example</title>\n");
out.write("</head>\n");
out.write("<body>\n");
out.println("The current date/time is " + new java.util.Date());
this.test(out, "Hi, Mom!");
out.write("\n");
out.write("</body>\n");
out.write("</html>\n");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try { out.clearBuffer(); } catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else log(t.getMessage(), t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
}
沒有什麼是正確的。你應該避免使用scripplets。總是使用JSTL – SpringLearner
從「java.lang」導入任何內容都很奇怪,因爲它已經默認導入;和靜態導入也很少使用(我只能在爲JUnit生成的代碼中看到它們)。在任何地方使用'System.out.println'更爲正常。無論如何,你應該認真考慮閱讀關於JSP的手冊/教程,因爲它看起來像你真的不知道你在做什麼。 – SJuan76
@SpringLearner我是學校的學生。但我會毫不猶豫地來到JSTL。 – WetWer