我在JSP boolean isPresent = false
中定义了一个变量,然后在一个包含的JSP中,我编写了代码来检查这个变量是否存在,但是获得NoSuchFieldException。
Class thisClass = this.getClass();
try {
Field field = thisClass.getDeclaredField("isPresent");
}
catch (Exception ex) {
//ToDo
}
想知道出了什么问题。
答案 0 :(得分:1)
如果您使用以下命令定义:
<%
boolean isPresent = false;
%>
该变量在从JSP生成的servlet的方法_jspService中定义,如下所示:
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
/// more code
boolean isPresent = false;
但是如果你将变量声明改为:
<%!
boolean isPresent = false;
%>
它会起作用!!
现在生成的Servlet:
public final class testing_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
boolean isPresent = false;
正如您现在所看到的,变量是范围类而非方法范围