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
outstream. - 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) %>
Most Recent jsp Faqs
- How to get the real requested URI from inside the error page?
- Can I define a method in a JSP page?
- What is the difference between request.getParameter() and request.getAttribute()?
- What is difference between page and pageContext in JSP pages?
- How to config a JSP file in web.xml?
- What is the difference between jsp:forward and response.sendRedirect?
- How to retrieve values from HTML form input elements in JSP?
Most Viewed jsp Faqs
- What is difference between page and pageContext in JSP pages?(10521)
- How to config a JSP file in web.xml?(8592)
- How to disable browser caching for a specific JSP?(7121)
- How to retrieve values from HTML form input elements in JSP?(6900)
- What is the difference between jsp:forward and response.sendRedirect?(5432)
- How to get the current JSP page name?(5407)
- What is the difference between request.getParameter() and request.getAttribute()?(4989)