Getting servlet init parameter that is defined in web.xml

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.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 {
                                ServletConfig config = getServletConfig();
                                System.out.println("Init parameter user name: " + config.getInitParameter("userName"));
                                System.out.println("Init parameter password: " + config.getInitParameter("password"));
                }
}


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


<servlet>
      <servlet-name>LoginController</servlet-name>
      <servlet-class>com.controller.LoginController</servlet-class>
      <init-param>
            <param-name>userName</param-name>
            <param-value>admin</param-value>
      </init-param>
      <init-param>
            <param-name>password</param-name>
            <param-value>password</param-value>
      </init-param>
  </servlet>
  <servlet-mapping>
      <servlet-name>LoginController</servlet-name>
      <url-pattern>/loginController</url-pattern>
  </servlet-mapping>


4. Run the servelet through browser, you can able to get the user name and password from servlet init parameter.

Comments

Popular Posts