如何从 JSP <%!...%>堵塞? [英] How to output HTML from JSP <%! ... %> block?

查看:12
本文介绍了如何从 JSP <%!...%>堵塞?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始学习 JSP 技术,遇到了一堵墙.

I just started learning JSP technology, and came across a wall.

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

这不起作用:

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

服务器说没有出局".

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

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.

JSP 页面由您的网络服务器转换为 Java servlet.例如,在 tomcats 中,scriptlet 中的所有内容(以<%"开头)以及所有静态 HTML 都被转换为一个巨大的 Java 方法,该方法将您的页面一行一行地写入一个名为out"的 JspWriter 实例.这就是您可以直接在 scriptlet 中使用out"参数的原因.另一方面,指令(以<%!"开头)被翻译为单独的 Java 方法.

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 &lt;%!...%>堵塞?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆