Set the context parameters in web.xml : Context « Servlets « Java






Set the context parameters in web.xml

// web.xml
/*
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" 
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
         http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
  <context-param>
    <param-name>name</param-name>
    <param-value>Joe</param-value>
  </context-param>
  <context-param>
    <param-name>password</param-name>
    <param-value>password</param-value>
  </context-param>

  <servlet>
    <servlet-name>ParameterServlet</servlet-name>
    <servlet-class>ParameterServlet</servlet-class>
    <init-param>
      <param-name>name</param-name>
      <param-value>Joe</param-value>
    </init-param>
    <init-param>
      <param-name>password</param-name>
      <param-value>password</param-value>
    </init-param>
  </servlet>
</web-app>
*/

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ParameterServlet extends HttpServlet {
  private String dbName = "";

  private String dbPassword = "";

  public void init(ServletConfig config) throws ServletException {
    super.init(config);
    ServletContext context = getServletContext();
    dbName = context.getInitParameter("name");
    dbPassword = context.getInitParameter("password");

  }

  public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws IOException {
    ServletOutputStream out = res.getOutputStream();
    res.setContentType("text/html");
    out.println("<html><head><title>Basic Servlet</title></head>");
    out.println("<body>Database username is  <b>" + dbName);
    out.println("</b><br>Database password is  <b>" + dbPassword + "</b>");
    out.println("</body></html>");
  }
}
           
       








Related examples in the same category

1.Servlets Context Sample
2.Servlets ServletContextListener Demo
3.Context log
4.Context logger
5.Context binder
6.Context accessor
7.Log in ServletContext
8.Context Attributes Servlet
9.Using Contexts Servlet
10.Context Parameters Servlet
11.Get settings from ServletContext