用Jsp编写代码时,有时候用<%! %>,有时候用<% %>,加不加感叹号,到底有什么不同吗?
这个问题,可以从Jsp生成的Java文件里,得到答案。
在Tomcat5.5中
hello.jsp
=========
<%@ page contentType="text/html; charset=gb2312" %>
<HTML>
<HEAD>
<TITLE></TITLE>
</HEAD>
<BODY>
<%! String hello = "hello"; %>
<%
String world = "world";
%>
</BODY>
</HTML>
所生成对应的java文件(E:\Tomcat4.1\work\Standalone\localhost\test\)
hello_jsp.java
==============
package org.apache.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import org.apache.jasper.runtime.*;
public class hello_jsp extends HttpJspBase {
String hello = "hello";
private static java.util.Vector _jspx_includes;
public java.util.List getIncludes() {
return _jspx_includes;
}
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
JspFactory _jspxFactory = null;
javax.servlet.jsp.PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
try {
_jspxFactory = JspFactory.getDefaultFactory();
response.setContentType("text/html; charset=gb2312");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write("\r\n");
out.write("<HTML>\r\n");
out.write("<HEAD>\r\n");
out.write("<TITLE>");
out.write("</TITLE>\r\n");
out.write("</HEAD>\r\n");
out.write("<BODY>\r\n");
out.write("\r\n");
String world = "world";
out.write("\r\n");
out.write("</BODY>\r\n");
out.write("</HTML>");
} catch (Throwable t) {
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (pageContext != null) pageContext.handlePageException(t);
} finally {
if (_jspxFactory != null) _jspxFactory.releasePageContext(pageContext);
}
}
}
注意粗体代码,可以得出如下结论:
<%! %>里声明的变量和方法都是作为类的属性和方法存在的,而<% %>里声明的变量则是作为_jspService这个方法的内部属性 (这也决定了<% %>里不能声明方法) 。
☉Java中String与Int怎样相互转换 (2009-10-22 19:9:16)
☉在Java里判断字符串是否相等 (2009-10-18 13:15:41)
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。