Sandeep Kumar Sandeep Kumar - 5 months ago 16
Java Question

check if variable is present by Reflection in JSP

I defined a variable in JSP

boolean isPresent = false
then in an included JSP I wrote code to check if this variable is present or not but getting NoSuchFieldException.

Class thisClass = this.getClass();
try {
Field field = thisClass.getDeclaredField("isPresent");
catch (Exception ex) {

Wondering what is wrong.


if you define it with:

    boolean isPresent = false;

the variable is defined in the method _jspService of the servlet generated from your JSP, like this:

  public void _jspService(HttpServletRequest request, HttpServletResponse response)
        throws, 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;

But if you change the declaration of variable to this:

     boolean isPresent = false;

it will work !!

Servlet generated now:

public final class testing_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {

    boolean isPresent = false;

As you can see now the variable is scope class and NOT method scope