Hi all,
I have written a simple ServletContextListener and set an attribute in it. when i am trying to retrieve the attribute value in my servlet, I am getting as null. Could anybody please let me know about this if i need to add any more changes.
Below is the complete code of my sample application
web.xml
-----------
<web-app>
<servlet>
<servlet-name>myServlet</servlet-name>
<servlet-class>com.mypackage.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>myServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<listener>
<listener-class>
com.mypackage.MyContextListener
</listener-class>
</listener>
<context-param>
<param-name>testMe</param-name>
<param-value>TestedSuccessfully</param-value>
</context-param>
</web-app>
ContextListener
---------------------
package com.mypackage;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class MyContextListener implements ServletContextListener{
public void contextDestroyed(ServletContextEvent arg0) {
}
public void contextInitialized(ServletContextEvent arg0) {
ServletContext context = arg0.getServletContext();
String testApplication = context.getInitParameter("testMe");
context.setAttribute("myTest", "mkmmkmmkm");
}
}
Servlet
----------
package com.mypackage;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyServlet extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response){
ServletContext context = getServletContext();
if(context != null){
response.setContentType("text/html");
try {
String output = (String) getServletContext().getAttribute("testMe");
PrintWriter out = response.getWriter();
out.print("The required value is... "+output);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
OUTPUT
---------------------------------------------------
When accessed with any url as below:
http://localhost:8080/helloworld/u
gettting output as "The required value is... null" . Because i set the context attribute, I am expecting not null. Can anybody suggest me on this.