gpt4 book ai didi

jsp - 如何从JSP输出HTML <%! ... %> 阻止?

转载 作者:行者123 更新时间:2023-12-03 07:48:14 29 4
gpt4 key购买 nike

我刚开始学习JSP技术,遇到了瓶颈。

如何从 <%! 中的方法输出 HTML ... %> JSP 声明 block ?

这不起作用:

<%! 
void someOutput() {
out.println("Some Output");
}
%>
...
<% someOutput(); %>

服务器说没有“out”。

U: 我确实知道如何使用返回字符串的方法重写代码,但是有没有办法在 <%!无效(){}%>?尽管它可能不是最佳的,但它仍然很有趣。

最佳答案

您不能在指令内使用“out”变量(也不能使用任何其他“预先声明的”脚本变量)。

JSP 页面由 Web 服务器转换为 Java servlet。例如,在 tomcats 内部,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";
}
}

关于jsp - 如何从JSP输出HTML <%! ... %> 阻止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/138999/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com