Are methods legal inside JSP scriptlet?

前端 未结 2 1861
陌清茗
陌清茗 2021-02-03 20:11

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:



        
相关标签:
2条回答
  • 2021-02-03 20:42

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

    <%! 
       public String doSomething(String param) { 
          // 
       } 
    %>
    <%
       String test = doSomething("test"); 
    %> 
    
    0 讨论(0)
  • 2021-02-03 20:49

    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

    0 讨论(0)
提交回复
热议问题