How to define Java mehtods in JSP pages?

Each JSP compiles to a separate class, so there are classes involved. If you are reusing the code chunks in the same JSP, then you can declare a method to appear in the JSP class. The JSP Declarations are used to declare variables and methods in the scripting language used in a JSP page. A declaration should be a complete declarative statement, or sequence thereof according to the syntax of the scripting language specified. The JSP declaration syntax is:

<%! declaration(s) %>
  • Declarations do not produce any output into the current out stream.
  • Declarations are initialized when the JSP page is initialized and are made available to othe declarations, scriptlets, and expressions.
  • Declarations declare methods global to the page.

For example,

<%! int x=0; } %>
<%! public void f(int i) { if (i<3) out.println(?...?); } %>

You don't get any direct handles to the implicit objects like request, response, page, out etc. For example,

<%!int foo(){out.println("--- message in declaration ---");  
int i = 10;  return i;}%>

You will get this error:

Undefined variable or class name: out 
out.println("--- message in declaration ---")

To work arround this problem, you need to pass out to the declared method as an argument:

<%!int foo(Writer out){out.println("--- message in declaration ---");  
int i = 10;  return i;}%>

and then would invoke it within your JSP body as

<% foo(out) %>

Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |