ServletConfig
- ServletConfig is one of the pre-defined interface.
- ServletConfig object is used for developing flexible servlets.
- ServletConfig objct exist one per servlet program.
- An object of ServletConfig created by the container during its initialization phase.
- An object of ServletConfig is available to the servlet during its execution, once the servlet execution is completed, automatically ServletConfig interface object will be removed by the container.
- An object of ServletConfig interface contains
details at web.xml, of a particular servlet. - The moment when we are using an object of ServletConfig, we need to configure the web.xml by writing
tag under tag of web.xml. - When ever compiler executes init() mehod then the ServletConfig will be created in general.
- An object of ServletConfig contain the
data in the form of key,value pairs, here the keys represents init param names and values are its values, which are represented in the web.xml file
How to Get ServletConfig Object into Servelt
Method1
ServletConfig conf = getServletConfig();
Method2
ServletConfig object will be available in init() method of the servlet.
public void init(ServletConfig config) { // ………………… }
How to Retrieve Data from ServletConfig Interface Object
public String getInitParameter(“param name”); public Enumeration getInitParameterNames();
web.xml
<web-app> <servlet> <servlet-name>onServletConfig</servlet-name> <servlet-class>java4s.OnServletConfig</servlet-class> <init-param> <param-name> n1 </param-name> <param-value> 100 </param-value> </init-param> . . </web-app>
Test.java
ServletConfig conf=getServletConfig(); String s1=conf.getInitParameter("n1");
ServletContext
An object of ServletContext is created by the web container at time of deploying the project. This object can be used to get configuration information from web.xml file. There is only one ServletContext object per web application.
Methods of ServletContext interface
- public String getInitParameter(String name):Returns the parameter value for the specified parameter name.
- public Enumeration getInitParameterNames():Returns the names of the context’s initialization parameters.
- public void setAttribute(String name,Object object):sets the given object in the application scope.
- public Object getAttribute(String name):Returns the attribute for the specified name.
- public Enumeration getInitParameterNames():Returns the names of the context’s initialization parameters as an Enumeration of String objects.
web.xml
<web-app> ...... <context-param> <param-name>parametername</param-name> <param-value>parametervalue</param-value> </context-param> ...... </web-app>
Test.java
ServletContext context=getServletContext(); //Getting the value of the initialization parameter and printing it String driverName=context.getInitParameter("parametername");