1

I want to access a variable in my inner class which is declared in my base class method. My base class is a servlet, so I cannot declare this variable as a global variable.

The following code will give you an idea. I want to access variable sort in my inner class which is declared in my base class servlet method

public class AccessPointsListServlet extends Servlet  {

    protected void execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String sort = null;
        sort = request.getParameter("Sort");

    }

    private class InnerClass {

        public int evaulate(String first){ 
            if (sort.equalsIgnoreCase("url")) {
            // some code         
            }
        }
    }

}

Please help

informatik01
  • 16,038
  • 10
  • 74
  • 104
Parag A
  • 443
  • 2
  • 8
  • 20
  • Using `getServletContext().setAttribute()` you are storing data in the **application scope**. Usually those are the attributes that are meant to be available to the whole web application (application scope) and for ALL users, plus they live as long as the web application lives. It is totally normal practice, just all depends on your concrete needs. Also see this answer that has more info and links related to different scopes and when you can use them: http://stackoverflow.com/a/14718683/814702 – informatik01 Mar 07 '13 at 15:33

1 Answers1

0

i think this is what you are looking for.

public class AccessPointsListServlet extends HttpServlet //instead of Servlet
{
    String sort=null;
    protected void execute(HttpServletRequest request, HttpServletResponse response) throws   Exception 
    {
        sort=request.getParameter("Sort");
    }
    private class InnerClass 
    {
        public int evaulate(String first)
        { 
            if (sort.equalsIgnoreCase("url"))
            {
                // some code         
            }
            //return int value here
        }
    }
}
Bhushan
  • 6,151
  • 13
  • 58
  • 91
  • I would have followed this approach. But my project expects me to avoid using global variables for Servlets. By the way I must mention AccessPointsListServlet extends class Abc and class Abc extends HttpServlet. Isn't it is a bad habit to have a global variable for a servlet? – Parag A Mar 05 '13 at 05:46
  • Hey there, I found another way of achieving this. I set the value of sort in my servlet method as follows. getServletContext().setAttribute("sort", request.getParameter("sort")); And then access this value of sort in my inner class as follows. String abc=(String)getServletContext().getAttribute("sort1"); Please let me know if this is normal and a better solution. – Parag A Mar 05 '13 at 17:50