ServletConfig

Servlet container uses the object of ServletConfig interface to provide the information to servlet during initialization. ServletConfig object fetch this information from web.xml file. So if we have to provide some dynamic information to servlet then we can pass it from web.xml file without making any change in our servlet class.

From servlet 3.0 we can also declare this information in servlet class itself. This can be done via annotations. Now we just required to pass the name with its value within @WebInitParam annotation. This annotation is present in javax.servlet.annotation.WebInitParam package.

Methods of ServletConfig

             Method

              Description

String getInitParameter(String name)

This method returns the value of specific parameter name.

Enumeration getInitParameterNames()

This method provides the enumeration of names.

ServletContext getServletContext()

This method returns the object of ServletContext.

String getServletName()

This method returns the name of servlet instance.

Example of ServletConfig interface

In this example, we are using annotations that contains subject as name and marks as it’s specific value.

DemoServletConfig.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.annotation.WebInitParam;
@WebServlet(
urlPatterns = {"/Demo"},initParams = {
@WebInitParam(name= "English", value="80"),
@WebInitParam(name= "Maths", value= "70"),
}
)
public class DemoServletConfig extends HttpServlet
{
 public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
 {
         res.setContentType("text/html");
         PrintWriter pw=res.getWriter();        
         ServletConfig con=getServletConfig();       
         String nm1=con.getInitParameter("English");
         String nm2=con.getInitParameter("Maths");         
         Integer int1=new Integer(nm1);
         Integer int2=new Integer(nm2);       
         int sum=int1+int2;      
         pw.println("<html><body>");
         pw.println("<h3>Marks in English="+int1+"</h3>");
         pw.println("<h3>Marks in Maths="+int2+"</h3>");
         pw.println("<h3>Total Marks="+sum+"</h3>");
         pw.println("</body></html>");         
 }
}
Output: