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 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;
public class LoginController extends HttpServlet {
      private static final long serialVersionUID = 1L;
       public LoginController() {
     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.


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


Popular Posts