Search code examples
javahtmljspscriptlet

How do I incorporate HTML code into my Java scriptlet method? (JSP)


I am trying to include HTML inside a java scriptlet method. A pseudocode example:

<%! public void doSomething() {
        %>
        <p>Hello World</p>
        <%   
} %>

The above example doesn't work because the compiler thinks that the method ends right after it's declared.

Is there an alternate way?


Solution

  • First, you really shouldn't be using scriptlets and especially shouldn't be defining methods in scriptlets.

    Nevertheless, you can print HTML with out.print() too, and even in a method defined in a scriptlet. You will run into the issue that in your declaration block you don't have access to out unless you declare a global JspWriter and set it to out lower down in your scriptlet, like below:

    <%! 
    JspWriter jout = null;
    public void doSomething() 
    {
       jout.print("<p>Hello World</p>");
    }
    %>
    <%
    jout = out;
    doSomething();
    %>