Servlet Pass Init Value in Web XML : web.xml « Servlet « Java Tutorial






import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;


public class MyServlet extends HttpServlet {

  int count;

  public void init() throws ServletException {
    String initial = getInitParameter("initial");
    try {
      count = Integer.parseInt(initial);
    }
    catch (NumberFormatException e) {
      count = 0;
    }
  }

  public void doGet(HttpServletRequest req, HttpServletResponse res)
                           throws ServletException, IOException {
    res.setContentType("text/plain");
    PrintWriter out = res.getWriter();
    count++;
    out.println("Since loading (and with a possible initialization");
    out.println("parameter figured in), this servlet has been accessed");
    out.println(count + " times.");
  }
}
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
    "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>
    <servlet><servlet-name>MyServletName</servlet-name>
             <servlet-class>MyServlet</servlet-class>
        <init-param>
            <param-name>
                initial
            </param-name>
            <param-value>
                1000
            </param-value>
            <description>
                The initial value for the counter  <!-- optional -->
            </description>
        </init-param>
             
    </servlet>
    
    <servlet-mapping><servlet-name>MyServletName</servlet-name>
        <url-pattern>/index.html</url-pattern>
    </servlet-mapping>
</web-app>
  Download:  ServletPassInitValueInWebXML.zip( 89 k)








25.30.web.xml
25.30.1.Servlet Web XML Context Init Parameter
25.30.2.Servlet Pass Init Value in Web XML
25.30.3.Servlet Map URL in web.XML
25.30.4.Set error page in web.xml
25.30.5.Define welcome files for web application
25.30.6.Set Servlet ContextListener in web.XML