37

I know its not recommended, and I should be using tag libraries etc etc.

But I'd still like to know if it is legal to declare methods in a JSP scriplet:

<%
   public String doSomething(String param) {
      //
   }

   String test = doSomething("test");

%>

Is that legal? I am getting some weird compile errors (like a ; is expected) that don't seem to fit. Thanks.

bluish
  • 26,356
  • 27
  • 122
  • 180
bba
  • 14,621
  • 11
  • 29
  • 26

2 Answers2

59

You need to use declaration syntax (<%! ... %>):

<%! 
   public String doSomething(String param) { 
      // 
   } 
%>
<%
   String test = doSomething("test"); 
%> 
axtavt
  • 239,438
  • 41
  • 511
  • 482
17

Understand the working of jsp :The entire JSP is converted to a Java class by Tomcat. This Java class is nothing but the Servlet. So it is the servlet that you will be running at the end.

Now consider that you are writing a Jsp code that prints the sum of 2 nos,passed in a method

<body>
  <%!               
  public int add(int a,int b)           
          {                                     
    return a+b;
          } 
   %>

  <% 
  int k;                
      k=add(5,6);
  %>

  <%=                   
      k                     
  %>

</body>

So if you were to write the same code that prints out sum of 2 nos in a servlet, you would probably write that in doGet() method.

The reason why you would get an error is you are defining a method within another method (which violates the rule of method definitions).

Hence we put the method in the definition tag so that if forms a new method

Saurabh Jain
  • 1,600
  • 1
  • 20
  • 30