Are methods legal inside JSP scriptlet?

谁都会走 提交于 2019-12-03 08:16:50

问题


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.


回答1:


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

<%! 
   public String doSomething(String param) { 
      // 
   } 
%>
<%
   String test = doSomething("test"); 
%> 



回答2:


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



来源:https://stackoverflow.com/questions/3769080/are-methods-legal-inside-jsp-scriptlet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!