0

Is there any way I can read getServletContext() in a normal static java method? i.e. a class which is not a servlet

My web.xml contains:

<context-param>
    <param-name>paramname</param-name>
    <param-value>test value</param-value>
  </context-param>

and static class:

public classname
{
    public static boolean methodname() 
    {
        String name=javax.servlet.GenericServlet.getServletContext().getInitParameter("paramname");

        // other processing
    }

}

I know I cannot access non-static method from a static class but trying to get a workaround.

I can do this is a servlet class. However my JSP page is calling a static method. Is there any workaround?

D. Rattansingh
  • 1,569
  • 3
  • 19
  • 30

1 Answers1

1

You cannot access it magically without first grabbing it at the first time where it is made available by the Servlet API's and then make it available as a static variable via a Util class.

For more places from where you can grab ServletContext check this link.

In the servlet

@Override
public void init(ServletConfig config) {
    ServletContext context = config.getServletContext();
    ServletConfigUtil.config = config;
}

and then you Util class

public class ServletConfigUtil {

public static ServletContext sc = null;

public static ServletContext  getServletContext(){
return sc ;
}
Shailendra
  • 8,874
  • 2
  • 28
  • 37