I am creating a simple web application. I need to get reference to ServletContext object in that class. How can i get it?
I am creating a simple web application. I need to get reference to ServletContext
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You’d better pass it as argument to the constructor of your object, or set it using a setter method.
In fact, you may obtain the context attribute that is relevant to your object and pass only it via constructor/setter. For example:
A much worse and more complication option is to:
ServletContextListener<listener><listener-class></listener-class></listener>contextInitialized(..)get theServletContextfrom the event and store it in a singleton – a static field somehwere.Alternatively, you can do this on each request, using a
ServletRequestListenerand store it in aThreadLocalinstead.Then you can obtain the value via calling your singleton/threadlocal holder like this: