How to output HTML from JSP block?

You can’t use the ‘out’ variable (nor any of the other “predeclared” scriptlet variables) inside directives.

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.

As an example, a very simple page (let’s call it foo.jsp):

            String someOutput() {
                return "Some output";
        <% someOutput(); %>

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(someOutput()); // i.e. write the results of the method call

    // Directive gets translated as separate method - note
    // there is no 'out' variable declared in scope
    private String someOutput()
        return "Some output";

Leave a Comment