The web app parameters that are configured in the deployment descriptor (web.xml) in the <context-para,> elements as shown in the xml below, can be retrieved by the servlet using the methods getInitParameter(String) & getInitParameterNames() of the ServletContext object.
The ServletContext object itself can be obtained by the servlets using the method getServletContext() which they inherit from their superclass GenericServlet.
Advantage of ServletContext
Usage of ServletContext Interface
- The object of ServletContext provides an interface between the container and servlet.
- The ServletContext object can be used to get configuration information from the web.xml file.
- The ServletContext object can be used to set, get or remove attribute from the web.xml file.
- The ServletContext object can be used to provide inter-application communication.
Example of ServletContext to get all the initialization parameters
In this example, we are getting all the initialization parameter from the web.xml file. For getting all the parameters, we have used the getInitParameterNames() method in the servlet class Demo.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Demo extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
ServletContext context=getServletContext();
Enumeration<String> e=context.getInitParameterNames();
String str="";
while(e.hasMoreElements()){
str=e.nextElement();
out.print("<br> "+context.getInitParameter(str));
}
}
} |
Web.xml
0 comments:
Post a Comment