Getting ServletContext init parameters that are defined in web.xml

In this example I am going to create some context parameter for performing database operation. The parameter names are
  a. DBUserName
  b. DBPassword
  c. DatabaseUrl
In servlet, I am going to get this details for performing database operation.

1. Create a new dynamic web project using eclipse.
2. Create a one new servlet and include the following code.
package com.controller;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/LoginController")
public class LoginController extends HttpServlet {
      private static final long serialVersionUID = 1L;
       public LoginController() {
        super();
    }
     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String userName = request.getParameter("userName");
            String password = request.getParameter("password");
            ServletConfig config = getServletConfig();
            ServletContext context = config.getServletContext();
            System.out.println("Context DB user name: " + context.getInitParameter("DBUserName"));
            System.out.println("Context DB password: " + context.getInitParameter("DBPassword"));
            System.out.println("Context DB URL: " + context.getInitParameter("DatabaseUrl"));
           //Database operation code goes here..!
      }
}


3. Update the web.xml file with following code.

<context-param>
      <param-name>DatabaseUrl</param-name>
      <param-value>http://10.10.10.10/TestDB</param-value>
  </context-param>
  <context-param>
      <param-name>DBUserName</param-name>
      <param-value>admin</param-value>
  </context-param>
  <context-param>
      <param-name>DBPassword</param-name>
      <param-value>admin</param-value>
  </context-param>


Once you run this servlet, the servlet will automatically get the database details from web.xml (context parameters).

Comments

Popular Posts