用Jsp編寫代碼時(shí),有時(shí)候用<%! %>,有時(shí)候用<% %>,加不加感嘆號(hào),到底有什么不同嗎?
這個(gè)問題,可以從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>
所生成對(duì)應(yīng)的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);
}
}
}
注意粗體代碼,可以得出如下結(jié)論:
<%! %>里聲明的變量和方法都是作為類的屬性和方法存在的,而<% %>里聲明的變量則是作為_jspService這個(gè)方法的內(nèi)部屬性 (這也決定了<% %>里不能聲明方法) 。