问题描述
我刚刚开始学习JSP技术,并且碰壁了.
I just started learning JSP technology, and came across a wall.
如何从<%!中的方法输出HTML! ...%> JSP声明块?
这不起作用:
<%!
void someOutput() {
out.println("Some Output");
}
%>
...
<% someOutput(); %>
服务器说没有出局".
U:我确实知道如何使用此方法返回字符串来重写代码,但是有一种方法可以在<%内部执行此操作! void(){}%>吗?尽管它可能不是最优的,但它仍然很有趣.
U: I do know how to rewrite code with this method returning a string, but is there a way to do this inside <%! void () { } %> ? Though it may be non-optimal, it's still interesting.
推荐答案
您不能在指令内部使用'out'变量(也不能使用其他任何预先声明的" scriptlet变量).
You can't use the 'out' variable (nor any of the other "predeclared" scriptlet variables) inside directives.
您的Web服务器将JSP页面转换为Java servlet.例如,在tomcat内部,scriptlet(以"
The JSP page gets translated by your webserver into a Java servlet. Inside tomcats, for instance, everything inside scriptlets (which start "<%"), along with all the static HTML, gets translated into one giant Java method which writes your page, line by line, to a JspWriter instance called "out". This is why you can use the "out" parameter directly in scriptlets. Directives, on the other hand (which start with "<%!") get translated as separate Java methods.
作为一个例子,一个非常简单的页面(我们将其称为foo.jsp):
As an example, a very simple page (let's call it foo.jsp):
<html>
<head/>
<body>
<%!
String someOutput() {
return "Some output";
}
%>
<% someOutput(); %>
</body>
</html>
最终将看起来像这样(为了清楚起见,忽略了很多细节):
would end up looking something like this (with a lot of the detail ignored for clarity):
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";
}
}
这篇关于如何从JSP<%输出HTML! ...%>堵塞?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!