Thursday, 19 September 2013

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 other declarations, scriptlets, and expressions.
  • Declarations declare methods global to the page.
Example:-

<%!

public String getMsg(String name){
String msg="Hi";
msg=msg+" "+name;
return msg;
}

%>

You can then invoke the function within scriptlets or expressions:
<%= getMsg("Ram") %>

No comments:

Post a Comment