我刚开始学习JSP技术,遇到了墙。 如何从%!中的方法输出HTML ...% JSP声明块? 这不工作: %! void someOutput() { out.println("Some Output");}%...% someOutput(); % 服务器说没有“out”。 U:我知道如
如何从<%!中的方法输出HTML ...%> JSP声明块?
这不工作:
<%!
void someOutput() {
out.println("Some Output");
}
%>
...
<% someOutput(); %>
服务器说没有“out”。
U:我知道如何重写代码,这个方法返回一个字符串,但是有一种方法,在<%! void(){}%> ?虽然它可能不是最优的,但它仍然很有趣。
您不能在指令内使用’out’变量(也不能使用任何其他“预声明”的scriptlet变量)。JSP页面由Web服务器转换为Java servlet。例如,在tomcat中,scriptlet(起始于“<%”)中的所有内容与所有静态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";
}
}
