question about the difference between <% and <%!

daocha 2010-06-07 11:34:32
I'm sorry that I can't type Chinese because the computer in our company has not been installed with a pinyin input method(The OS language is traditional Chinese) but I'm not authorized to install any software. It's the company's rule.
The question is the difference between "<% %>" and "<%! %>".
I know the code in <%! %> is declaration and no output is allowed in the exclamation point(<%! %>) while any correct java code is allowed in <% %>.
It means only variable and method declaration is allowed in <%! %> and the declaration statement should be complete java statement and it must end with a semicolon.
Example using "<%!":
<%!
public String str="hello";
public void Test()
{
}
%>

But we can also declare variable and method in <% %>.
Example using "<%":
<%
public String str="hello";
public void Test()
{
}
%>

The question is why we still need a exclamation point(<%!) to write a declaration statement? When do we have to use <%!%> only?

Thanks.
...全文
98 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
Java技术栈 2010-06-07
  • 打赏
  • 举报
回复
<%! %> 用于变量的声明!
<% %> 可以用来声明变量,但也可以用来写程序代码块,比方说out.print(),但是<%!%>就不可以.
daocha 2010-06-07
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 thc1987 的回复:]

<% int i = 99; %>
这样的时候,当jsp页面转换成servlet时,会在这个servlet的_jspService()方法中申明一个变量int i = 99;这里的i在方法体里面所以你每次请求jsp页面时,这个变量i都是要重新赋值的

<%! int i = 99; %>
这样的时候,当jsp页面转换成servlet时,会在这个servlet的_jspService()方……
[/Quote]

I got it.... I finally memorize that, in that case , the method declaration can't be put in <%%> .. method declaration should be put in <%!%> but for the variable, in <%!%> and in <%%> are both ok
jxg1981 2010-06-07
  • 打赏
  • 举报
回复
jsp本质上就是servlet!!!<%! %>在这里面定义的变量和函数是类的成员变量和成员方法。在<% %>定义的变量和方法是_jspService()方法中的局部变量和方法。你可以到 \work\Catalina\localhost\你的项目名字下找到jsp编译后相应的java文件一看就知道两者的区别了。希望能帮到你
TXJ_NO1 2010-06-07
  • 打赏
  • 举报
回复
<%! %> 用于变量的声明!
<% %> 可以用来声明变量,但也可以用来写程序代码块,比方说out.print(),但是<%!%>就不可以.
猿敲月下码 2010-06-07
  • 打赏
  • 举报
回复
<% int i = 99; %>
这样的时候,当jsp页面转换成servlet时,会在这个servlet的_jspService()方法中申明一个变量int i = 99;这里的i在方法体里面所以你每次请求jsp页面时,这个变量i都是要重新赋值的

<%! int i = 99; %>
这样的时候,当jsp页面转换成servlet时,会在这个servlet的_jspService()方法申明一个变量int i = 99;也就是我们所说的成员变量(没有全局变量的说法),所以你刷新页面时i的值依然是不变的.

用户对同一个servlet的多个请求会产生多个线程,但是如果这个servlet没有实现SingleThreadModel接口,则每个线程都是调用同一个servlet的service方法.


你也可以在Tomcat下的work\Catalina\localhost\项目名 中查看对应jsp转换成servlet的类
bjtu1005 2010-06-07
  • 打赏
  • 举报
回复
Well,during your question I can know many things ,Although I don't know how to answer your question ,I will up you! I hope you can get answers from csdn .
jichenglu911 2010-06-07
  • 打赏
  • 举报
回复
个人认为啊,在<%%>里面,就相当于再.java里面去编写任何代码,也就是说,在<%%>里面可以做任何事情,而在<%!%>里面只能声明变量和方法,至于为什么<%!%>会存在,我个人考虑可能是在<%!%>里面声明要比<%%>里面声明编译起来效率会高些(比如说机器一看就知道这个是声明的,所以会快些?)
daocha 2010-06-07
  • 打赏
  • 举报
回复
up
help me

81,094

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧