I just started learning JSP technology, and came across a wall.
How do you output HTML from a method in <%! ... %> JSP declaration block?
This doesn't work:
<%! void someOutput() { out.println("Some Output"); } %> ... <% someOutput(); %>
Server says there's no “out”.
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.
The JSP engine compiles the servlet into an executable class and forwards the original request to a servlet engine. A part of the web server called the servlet engine loads the Servlet class and executes it. During execution, the servlet produces an output in HTML format.
You can just put the jsp in one of the default apps (or in one of yours if you have), get it from a browser and save the HTML file. It is much more work but it may worth it if : you have to do that on multiple JSP. you want to be sure of how a Java EE or servlet container would translate the file.
A scriptlet tag is used to execute java source code in JSP. Syntax is as follows: <% java source code %>
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):
<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"; } }
<%! private void myFunc(String Bits, javax.servlet.jsp.JspWriter myOut) { try{ myOut.println("<div>"+Bits+"</div>"); } catch(Exception eek) { } } %> ... <% myFunc("more difficult than it should be",out); %>
Try this, it worked for me!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With