Are methods legal inside JSP scriptlet?

前端 未结 2 1863
陌清茗
陌清茗 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: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

    
      <%!               
      public int add(int a,int b)           
              {                                     
        return a+b;
              } 
       %>
    
      <% 
      int k;                
          k=add(5,6);
      %>
    
      <%=                   
          k                     
      %>
    
    
    

    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

提交回复
热议问题