JSP scriptlet 中的方法合法吗?
我知道不推荐这样做,我应该使用标签库等。
但我仍然想知道在 JSP scriplet 中声明方法是否合法:
<%
public String doSomething(String param) {
//
}
String test = doSomething("test");
%>
这合法吗?我收到一些奇怪的编译错误(例如 a ; is Expected
),这些错误似乎不合适。谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要使用声明语法(
<%! ... %>
):You need to use declaration syntax (
<%! ... %>
):了解jsp的工作:整个JSP被Tomcat转换为Java类。这个 Java 类只不过是 Servlet。所以您最后将运行的是 servlet。
现在考虑您正在编写一个 Jsp 代码来打印 2 个 no 的总和,并在方法中传递
因此,如果您要编写在 servlet 中打印出 2 个 no 的总和的相同代码,您将可能会写在 doGet() 方法中。
出现错误的原因是您在另一个方法中定义一个方法(这违反了方法定义的规则)。
因此我们将方法放在定义标签中,这样if就形成了一个新方法
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
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