Java JSP scriptlet 中的方法是否合法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3769080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 04:40:40  来源:igfitidea点击:

Are methods legal inside JSP scriptlet?

javajspmethodsscriptlet

提问by bba

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:

但我还是想知道在 JSP 脚本中声明方法是否合法:

<%
   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.

这是合法的吗?我收到了一些a ; is expected似乎不合适的奇怪编译错误(如)。谢谢。

采纳答案by axtavt

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

您需要使用声明语法 ( <%! ... %>):

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

回答by Saurabh Jain

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.

理解jsp的工作原理:整个JSP被Tomcat转换成Java类。这个 Java 类不过是 Servlet。因此,您将在最后运行 servlet。

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

现在考虑您正在编写一个 Jsp 代码,该代码打印 2 个 nos 的总和,并在方法中传递

<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.

因此,如果您要编写在 servlet 中打印出 2 个 nos 之和的相同代码,您可能会在 doGet() 方法中编写它。

The reasonwhy 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

因此我们将方法放在定义标签中,以便 if 形成一个新方法