How to create a function in a jsp page?

Hi,

Is it possible to create functions within a jsp page? I'm trying something like the following attached code, but no luck. How do we do this?

Thanks
<%!
  private void makeSomeUiStuff() {
      %> <p> Hello world! </p> <%
  }
%>

<%
  makeSomeUiStuff();
%>

Open in new window

DJ_AM_JuiceboxAsked:
Who is Participating?
 
rrzCommented:
When a JSP is translated to java code(a servlet), code written in scriptlets is placed in the _jspService method. When we declare a method in a JSP it is translated to a method in the servlet. Implicit JSP objects are defined in the _jspService method.  Therefore if you want to print something from your method, then you must send "out"(a implicit object) as a parameter. All this is clear if you look at the translation file. In Tomcat, look in its work folder for that file. Here is an example.
<%@ page import="java.io.IOException" %>
<%!
  private void makeSomeUiStuff(JspWriter out) throws IOException{
       out.print("<html><body><p> Hello world! </p></body></html>"); 
  }
%>
<%
  makeSomeUiStuff(out);
%>

Open in new window

0
 
BitsqueezerCommented:
Hi,

sure, here's a thread which answers your question:

http://www.velocityreviews.com/forums/t140523-jsp-functions-methods-page-question.html

Cheers,

Christian
0
 
rrzCommented:
You could also do it this way.
<%@ page import="java.io.IOException" %>
<%!
  private String makeSomeUiStuff() throws IOException{
       return "<html><body><p> Hello world2! </p></body></html>"; 
  }
%>
<%
  out.print(makeSomeUiStuff());
%>

Open in new window

0
 
jocafiCommented:
In order to make your jsp more organized and cleaner, you should create your own java library and put your function there.

Do not forget to put your library under ${your_web_app}/WEB-INF/lib

See the example below how to import and use your class.
<%@page import="org.mylib.MyClass"%>

...
<%
  MyClass instance = new MyClass();
  // make one thing
  instance.makeSomeUiStuff(out);
  // make other thing
  out.print(instance.makeOtherUiStuff());
%>

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.