In this section, you will learn how to get the context parameters which we have given in the web.xml file.
In this section, you will learn how to get the context parameters which we have given in the web.xml file.In this section, you will learn how to get the context parameters which we have given in the web.xml file. ServletContext is a interface which helps us to communicate with the servlet container. There is only one Servlet Context for the entire web application and the components of the web application can share it.
Web application initialization:
In web.xml, do the following:
<servlet> <servlet-name>GettingContextParameterNames</servlet-name> <servlet-class>GettingContextParameterNames</servlet-class> </servlet> <servlet-mapping> <servlet-name>GettingContextParameterNames</servlet-name> <url-pattern>/GettingContextParameterNames</url-pattern> </servlet-mapping> <context-param> <param-name>username</param-name> <param-value>roseindia</param-value> </context-param> <context-param> <param-name>password</param-name> <param-value>roseindia</param-value> </context-param> |
Here is the code:
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class GettingContextParameterNames extends HttpServlet { private String user = ""; private String pass = ""; public void init(ServletConfig config) throws ServletException { super.init(config); ServletContext context = getServletContext(); user = context.getInitParameter("username"); pass = context.getInitParameter("password"); } public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException { ServletOutputStream out = res.getOutputStream(); res.setContentType("text/html"); out.println("Username is: " + user); out.println("Password is: " + pass + ""); } }
Output
Username is: roseindia Password is: roseindia