Nov
29
2015

get servletContext object in simple java class

In this post of servlet tutorial we will see how to get get servletContext object in simple java class. Few days back i encounter problem related to servletContext. In my problem i was need to get getRealPath of upload folder in my application deployment directory. The pain point of the problem was that eclipse deploy application in .metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\ directory but in production environment this path is different. To get real path of any file in application deployment repository we may use servletcontext object. 

To get servletcontext in simple java class we need to implements ServletContextListener in a class . In ServletContextListener we may take a a field of ServletContext type and can access this field in any class in application.

Class that implements ServletContextListener can also be used to do other stuff in application startup phase. For example creating JDBC connection and other type of initialization task. Such class also need to be register as listener in web.xml. Let see the class that implement ServletContextListener

ServletContextListner.java

In ServletContextListner class i have set attribute friendListin setvletcontext object which we can access any where in application now. On application startup contextInitialized method is invoked . Here in this method we can also do other task like making jdbc connection or fetching some values from DB after creating connection etc.

web.xml

We need to register ServletContextListener implementation class as listener in web.xml.

TestApplicationContext.java

in TestApplicationContext class we have accessed attribute that set up at application initialization time in ServletContextListner class. Also we have printed path of web.xml file of our application. When i invoked testApplicationContext() method of TestApplicationContext class i got this output on my console

Ankit Jain
Ankush Jain
Devender Kumar
Dheeraj Chaudhary
Kishor Kumar Mali
Kuldeep Mishra
Narayan Lal
D:\git\spring-file-upload\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\ServletCntxInJavaClass\web.xml

This is all in this post of servlet tutorial. hpe this was useful to you. If you find any scope of improvment in it please do share it with me.

Related Posts

About the Author: devender kumar

java/j2EE developer

Comments are closed.