Getting Context Parameter Names


 

Getting Context Parameter Names

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.
Getting Context Parameters Names

Getting Context Parameter Names

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:

  1. First of all the web container reads the deployment descriptor file and then creates a name/value pair for each <context-param> tag.
  2. After creating the name/value pair it creates a new instance of ServletContext.
  3. Its the responsibility of the Container to give the reference of the ServletContext to the context init parameters.
  4. The servlet and jsp which are part of the same web application can have the access of the ServletContext.

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

Ads