In this tutorial, we will discuss about ServletConfig Interface.
In this tutorial, we will discuss about ServletConfig Interface.In this tutorial, we will discuss about ServletConfig Interface.
ServletConfig Interface :
The servlet container uses a ServletConfig object to pass initialization information to the servlet. In general it is used to read the initialization parameters so whenever server wants to pass initialization data to a servlet, it creates a class which implements this interface.
This interface has following four methods -
Example :
ServletConfigExample.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServletConfigExample extends HttpServlet {
int counter;
public void init() throws ServletException {
String initValue = getServletConfig().getInitParameter("count");
counter = Integer.parseInt(initValue);
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
counter++;
out.println("You accessed this servlet " + counter + " times");
}
}
web.xml -
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>ServletConfigExample</display-name> <servlet> <servlet-name>ServletConfigExample</servlet-name> <servlet-class>ServletConfigExample</servlet-class> <init-param> <param-name>count</param-name> <param-value>0</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>ServletConfigExample</servlet-name> <url-pattern>/servletConfig</url-pattern> </servlet-mapping> </web-app>
Output :