SlideShare a Scribd company logo
1 of 18
Download to read offline
ServletConfig & ServletContext :-
ß Suppose let us here we have multiple servlet. Here there are three servlet A, B, C
under classes’ folder. If you want to give any input to all the servlet A, B, C
servlet.
ß I want to pass the same connection object to AServlet , BServlet, CServlet.
Suppose I have a JDBC connection object, I want to give that object to AServlet,
BServlet, CServlet.
ß I have only one resource I want to share that resource to all servlet then what
should will do- it makes as.
ASHUTOSH TRIVEDI
Email:trivedi.ashutosh2013@gmail.com
MNO—9580074408
Read ServletConfig & ServletContext by ASHUTOSH
ß I have a single resource if I want to share same resource to all the user then
resource need to become to public resource.
ß 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.
ß It is one per web application. So it is called as the global memory of web
application.
ß ServletContext object means it is the object of a java class (container supplier)
implementing javax.servlet.ServletConext interface.
ß Servlet container creates this object either during deployment of the web
application or during server start-up.
ß Servlet container destroys this object automatically when web application is
undeployed or reloaded or stopped or when server is stopped/ re-started.
¸ An object of ServletContext is created by the web container at the time of deploying
the project.
¸ There is only one ServletContext object per web application.
¸ This Servletcontext object can be used to get configuration information from
web.xml file. If any information is shared to many object, it is better to provide it
from the web.xml file using the <context-param> element.
¸ Easy to maintain if any information is shared to all the servlet it is better to make it
available for all the servlet. We provide this information from the web.xml, so if the
information is changer we don't need to modify the servlet. Thus if removes
maintenance problem.
¸ Every web Application runs in a separate context which isolates it from another
application running in the same server.
¸ Defines a set of methods that a servlet uses to communicate with its servlet container,
for example to get the MIME type of a file dispatch requests or write to a log file.
¸ For every Servlet, web container will create one ServletConfig object to maintain
Servlet level initialization parameter. By using this object Servlet can get its
configuration information.
¸ Similarly for every web-application webcontainer creates one ServletContext object
to maintain application level configuration information.
¸ Servlet can get application level configuration information through this context
object only.
¸ ServletConfig per Servlet, whereas ServletContext per Web-application.
¸ If initialization parameters are common for all Servlets then it is not recommended to
declare those parameters at Servlet level , we have to declare such type of parameters
at application -level by using < context-param >
<web-app>
<context-param>
<param-name>username</param-name>
<param-value>scott</param-value>
</context-param>
</web-app>
¸ We can declare any number of context parameters but one < context-param > for each
Servlet.
¸ < context-param > is the direct child tag of <web-app > & hence we can declare
anywhere within <web-app>
¸ The context initialization parameters are available throughout the web-application
anywhere.
¸ If we want to use same init-parameters then we can declare at context-level as
<context-param>
<param-name>username</param-name>
<param-value>scott</param-value>
</context-param>
¸ Within the Servlet we can access these context initialization parameters by using
ServletContext object.
How to Get ServletContext Object into Our Servlet Class
∑ In servlet programming we have 3 approaches for obtaining an object of
ServletContext interface.
Way 1.
Syntax-
//We can get ServletContext object from ServletConfig
ServletConfig conf = getServletConfig();
ServletContext context = conf.getServletContext();
∑ First obtain an object of ServletConfig interface ServletConfig interface contain
direct method to get Context object, getServletContext();.
Way 2.
∑ Direct approach, just call getServletContext() method available in GenericServlet
[pre-defined]. In general we are extending our class with HttpServlet, but we know
HttpServlet is the sub class of GenericServlet.
Syntax-
//Another convenient way to get ServletContext object
ServletContext context = getServletContext();
Way 3.
∑ We can get the object of ServletContext by making use of HttpServletRequest
object, we have direct method in HttpServletRequest interface.
Syntax:-
public class MyJava extends HttpServlet
{
public void doGet/doPost(HttpServletRequest req,-)
{
ServletContext ctx = req.getServletContext();
}
}
Commonly used methods of ServletContext interface
There is given some commonly used methods of ServletContext interface.
1. public String getInitParameter(String name):Returns the parameter value for the
specified parameter name.
2. public Enumeration getInitParameterNames():Returns the names of the context's
initialization parameters.
3. public void setAttribute(String name,Object object):sets the given object in the
application scope.
4. public Object getAttribute(String name):Returns the attribute for the specified
name.
5. public Enumeration getInitParameterNames():Returns the names of the context's
initialization parameters as an Enumeration of String objects.
6. public void removeAttribute(String name):Removes the attribute with the given
name from the servlet context.
Syntax to provide the initialization parameter in Context scope
∑ The context-param element, subelement of web-app, is used to define the initialization
parameter in the application scope. The param-name and param-value are the sub-
elements of the context-param. The param-name element defines parameter name and
and param-value defines its value.
web.xml
<web-app>
....
<context-param>
<param-name>parametername</param-name>
<param-value>parametervalue</param-value>
</context-param>
...
</web-app>
Example of ServletContext to get the initialization parameter
∑ In this example, we are getting the initialization parameter from the web.xml file and
printing the value of the initialization parameter. Notice that the object of ServletContext
represents the application scope. So if we change the value of the parameter from the
web.xml file, all the servlet classes will get the changed value. So we don't need to
modify the servlet. So it is better to have the common information for most of the
servlets in the web.xml file by context-param element. Let's see the simple example:
web.xml
<web-app>
....
<display-name> HelloGenericServlet </display-name>
<description>
This is a simple web application with a source code .
</description>
<context-param>
<param-name>drivername</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</context-param>
<context-param>
<param-name>username</param-name>
<param-value>system</param-value>
</context-param>
<context-param>
<param-name>password</param-name>
<param-value>oracle</param-value>
</context-param>
<servlet>
<servlet-name> context </servlet-name>
<servlet-class> ServletContextDemoServlet </servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> context</servlet-name>
<url-pattern> /context </url-pattern>
</servlet-mapping>
...
import java.io.*;
import javax.servlet.*;
public class ServletContextDemoServlet implements HttpServlet{
private static final long serialVersionUID=11;
ServletConfig config=null;
public void init() throws ServletException
{
System.out.println("-----------------------------------------------------------------");
System.out.println("init method is called in "+ this.getClass().getName());
System.out.println("-----------------------------------------------------------------");
}
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws IOException,ServletException{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
ServletContext context=getServletContext();
out.print("<b> Read specific InitParam using context.getInitParameter(String paramName
</b> <br> <br>");
String driverName=context.getInitParameter("drivername");
out.print(driverName+"<br><br>")
out.print("<b> Read All InitParameters using getInitParameterNames() method </b> <br>");
Enumeration<String> initParamNamesEnum=context.getInitParameterNames();
String paramName="";
while (initParamNamesEnum.hasMoreElements())
{
paramName = initParamNamesEnum.nextElement();
paramValue= context.getInitParameter(paramName);
out.print("<br> "+ paramName + ": " + paramValue);
}
System.out.println("-----------------------------------------------------------------");
System.out.println("sevice method has been called ");
System.out.println("-----------------------------------------------------------------");
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello generic servlet</b>");
out.print ("<br>");
out.print("</body></html>");
}
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws IOException,ServletException
{
doGet(request, response)
}
public void destroy()
{
System.out.println("-----------------------------------------------------------------");
System.out.println("destroy method has been called and servlet is destroyed ");
System.out.println("-----------------------------------------------------------------");
}
}
// Index.html
<html>
<head><title>Context test</title>
<body>
<li><a href="context">Context Test</a></li>
</body>
</html>
ServletConfig (one per SERVLET):
¸ ServletConfig is an interface which is present in javax.servlet.* package.
¸ The purpose of ServletConfig is to pass some initial parameter values, technical
information (driver name, database name, data source name, etc.) to a servlet.
¸ An object of ServletConfig will be created one per servlet.
¸ An object of ServletConfig will be created by the server at the time of executing
public void init (ServletConfig) method.
¸ An object of ServletConfig cannot be accessed in the default constructor of a Servlet
class.Since, at the time of executing default constructor ServletConfig object does not
exist.
¸ By default ServletConfig object can be accessed with in init () method only but not in
doGet and doPost. In order to use, in the entire servlet preserve the reference of
ServletConfig into another variable and declare this variable into a Servlet class as a
data member of ServletConfig.
v When we want to give some global data to a servlet we must obtain an object of
ServletConfig.
v web.xml entries for ServletConfig
<servlet>
………….
<init-param>
<param-name>Name of the parameter</param-name>
<param-value>Value of the parameter</param-value>
</init-param>
………….
</servlet>
For example:
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>serv1</servlet-class>
<init-param>
<param-name>v1</param-name>
<param-value>10</param-value>
</init-param>
<init-param>
<param name>v2</param name>
<param-value>20</param-value>
</init-param>
</servlet>
ÿ The data which is available in ServletConfig object is in the form of (key, vlaue)
OBTAINING an object of ServletConfig:
v An object of ServletConfig can be obtained in two ways, they are by calling
getServletConfig() method and by calling init (ServletConfig).
v Within the Servlet we can get its Config object as follows.
ServletConfig config=getServletConfig();
By calling getServletConfig () method:
v getServletConfig() is the method which is available in javax.servlet.Servlet interface.
This method is further inherited and defined into a class called
javax.servlet.GenericServlet and that method is further inherited into another predefined
class called javax.servlet.http.HttpServlet and it can be inherited into our own servlet
class.
For example:
public class serv1 extends HttpServlet
{
public void doGet (HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
…………
…………
ServletConfig config=this.getServletConfig ();
…………
…………
}
}
In the above example an object config contains (key, value) pair data of web.xml file which
are written under <init-param> tag of <servlet> tag.
v By calling init (ServletConfig):
For example:
public class serv2 extends HttpServlet
{
ServletConfig sc;
public void init (ServletConfig sc)
{
Super.init (sc); // used for calling init (ServletConfig) method of HttpServlet
this.sc=sc; // ServletConfig object sc is referenced
}
…………
…………
};
RETRIEVING DATA from ServletConfig interface object:
∑ In order to get the data from ServletConfig interface object we must use the following
methods:
public String getInitParameter (String); ____________ 1
public Enumeration getInitParameterNames (); ________ 2
v Method-1 is used for obtaining the parameter value by passing parameter name
Key Value
V1 10
V2 20
V3 30
Parameter-name Parameter-value
String val1=config.getInitParameter (“v1”);
String val2=config.getInitParameter (“v2”);
String val3=config.getInitParameter (“v3”);
vMethod-2 is used for obtaining all parameter names and their corresponding parameter
values.
For example:
Enumeration en=config.getInitParameterNames ();
while (en.hasMoreElements ())
{
Object obj=en.nextElement ();
String pname= (String) obj;
String pvalue=config.getInitParameter (pname);
out.println (pvalue+” is the value of ”+pname);
}
Serv1.java:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class Serv1 extends HttpServlet
{
public void doGet (HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
res.setContentType ("text/html");
PrintWriter pw=res.getWriter ();
ServletConfig config=getServletConfig ();
String val1=config.getInitParameter ("v1");
String val2=config.getInitParameter ("v2");
String val3=config.getInitParameter ("v3");
String val4=config.getInitParameter ("v4");
pw.println ("<h3> Value of v1 is "+val1+"</h3>");
pw.println ("<h3> Value of v2 is "+val2+"</h3>");
pw.println ("<h3> Value of v3 is "+val3+"</h3>");
pw.println ("<h3> Value of v4 is "+val4+"</h3>");
}
};
Serv2.java:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class Serv2 extends HttpServlet
{
public void doGet (HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
res.setContentType ("text/html");
PrintWriter pw=res.getWriter ();
ServletConfig config=getServletConfig ();
Enumeration en=config.getInitParameterNames ();
while (en.hasMoreElements ())
{
Object obj=en.nextElement ();
String pname= (String) obj;
String pvalue=config.getInitParameter (pname);
pw.println ("</h2>"+pvalue+" is the value of "+pname+"</h2>");
}
}
}
web.xml:
<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>Serv1</servlet-class>
<init-param>
<param-name>v1</param-name>
<param-value>10</param-value>
</init-param>
<init-param>
<param-name>v2</param-name>
<param-value>20</param-value>
</init-param>
</servlet>
<servlet>
<servlet-name>pqr</servlet-name>
<servlet-class>Serv2</servlet-class>
<init-param>
<param-name>v3</param-name>
<param-value>30</param-value>
</init-param>
<init-param>
<param-name>v4</param-name>
<param-value>40</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/firstserv</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>pqr</servlet-name>
<url-pattern>/secondserv</url-pattern>
</servlet-mapping>
</web-app>
v Develop a flexible servlet that should display the data of the database irrespective
driver name, tablename and dsn name?
Answer:
DbServ.java:
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.io.*;
public class DbServ extends HttpServlet
{
ServletConfig sc=null;
public void init (ServletConfig sc) throws ServletException
{
super.init (sc);
this.sc=sc;
}
public void doGet (HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
res.setContentType ("text/html");
PrintWriter pw=res.getWriter ();
String dname=sc.getInitParameter ("dname");
String url=sc.getInitParameter ("url");
String tab=sc.getInitParameter ("tab");
try
{
Class.forName (dname);
Connection con=DriverManager.getConnection (url,"scott","tiger");
Statement st=con.createStatement ();
ResultSet rs=st.executeQuery ("select * from "+tab);
while (rs.next ())
{
pw.println ("<h2>"+rs.getString (1)+""+rs.getString (2)+""+rs.getString (3)+"</h2>");
}
con.close ();
}
catch (Exception e)
{
res.sendError (503,"PROBLEM IN DATABASE...");
}
}
};
web.xml:
<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>DbServ</servlet-class>
<init-param>
<param-name>dname</param-name>
<param-value>oracle.jdbc.driver.OracleDriver ()</param-value>
</init-param>
<init-param>
<param-name>url</param-name>
<param-value>jdbc:oracle:thin:@localhost:1521:xe</param-value>
</init-param>
<init-param>
<param-name>tab</param-name>
<param-value>emp</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/dbdata</url-pattern>
</servlet-mapping>
</web-app>
Property Servlet init-param Servlet context-param
1. declaration
By using init-param with in
servlet.
<servlet>
<init-param>
<param-name>
<param-value>
</init-param>
</servlet>
By using init-param with in
web-app.
<servlet>
<context-param>
<param-name>
<param-value>
</context-param>
</servlet>
2. Servlet code to
Access the parameter
String
value=getInitParameter("pname")
;
(or)
String value=getServletConfig(
).getInitParameter("pname");
String
value=getServletContext(
).getInitParameter("pname")
;
(or)
String
value=getServletConfig(
).getServletContext(
).getInitParameter("pname")
;
3. Availability(Scope)
Available only for a particular
Servlet in which <init-param> is
declared.
Available for all Servlet's &
Jsp's within the web-
application.

More Related Content

What's hot

Java collections concept
Java collections conceptJava collections concept
Java collections conceptkumar gaurav
 
Spring Framework
Spring Framework  Spring Framework
Spring Framework tola99
 
A brief introduction to SQLite PPT
A brief introduction to SQLite PPTA brief introduction to SQLite PPT
A brief introduction to SQLite PPTJavaTpoint
 
Elastic Stack 을 이용한 게임 서비스 통합 로깅 플랫폼 - elastic{on} 2019 Seoul
Elastic Stack 을 이용한 게임 서비스 통합 로깅 플랫폼 - elastic{on} 2019 SeoulElastic Stack 을 이용한 게임 서비스 통합 로깅 플랫폼 - elastic{on} 2019 Seoul
Elastic Stack 을 이용한 게임 서비스 통합 로깅 플랫폼 - elastic{on} 2019 SeoulSeungYong Oh
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js ExpressEyal Vardi
 
Oracle数据库高级安全选件ASO介绍
Oracle数据库高级安全选件ASO介绍Oracle数据库高级安全选件ASO介绍
Oracle数据库高级安全选件ASO介绍jenkin
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentationguest11106b
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivityVaishali Modi
 
Using Magento 2.3 MySQL Queues
Using Magento 2.3 MySQL QueuesUsing Magento 2.3 MySQL Queues
Using Magento 2.3 MySQL QueuesRenu Mishra
 
About elasticsearch
About elasticsearchAbout elasticsearch
About elasticsearchMinsoo Jun
 
Java Design Patterns Tutorial | Edureka
Java Design Patterns Tutorial | EdurekaJava Design Patterns Tutorial | Edureka
Java Design Patterns Tutorial | EdurekaEdureka!
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introductionRasheed Waraich
 
Developing an ASP.NET Web Application
Developing an ASP.NET Web ApplicationDeveloping an ASP.NET Web Application
Developing an ASP.NET Web ApplicationRishi Kothari
 
Bombardier adobe aem msm implementation
Bombardier adobe aem msm implementationBombardier adobe aem msm implementation
Bombardier adobe aem msm implementationKen Knitter
 

What's hot (20)

Servlets api overview
Servlets api overviewServlets api overview
Servlets api overview
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
Spring Framework
Spring Framework  Spring Framework
Spring Framework
 
A brief introduction to SQLite PPT
A brief introduction to SQLite PPTA brief introduction to SQLite PPT
A brief introduction to SQLite PPT
 
Elastic Stack 을 이용한 게임 서비스 통합 로깅 플랫폼 - elastic{on} 2019 Seoul
Elastic Stack 을 이용한 게임 서비스 통합 로깅 플랫폼 - elastic{on} 2019 SeoulElastic Stack 을 이용한 게임 서비스 통합 로깅 플랫폼 - elastic{on} 2019 Seoul
Elastic Stack 을 이용한 게임 서비스 통합 로깅 플랫폼 - elastic{on} 2019 Seoul
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
 
Java Script ppt
Java Script pptJava Script ppt
Java Script ppt
 
Flask
FlaskFlask
Flask
 
Oracle数据库高级安全选件ASO介绍
Oracle数据库高级安全选件ASO介绍Oracle数据库高级安全选件ASO介绍
Oracle数据库高级安全选件ASO介绍
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
 
Jsp presentation
Jsp presentationJsp presentation
Jsp presentation
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
Using Magento 2.3 MySQL Queues
Using Magento 2.3 MySQL QueuesUsing Magento 2.3 MySQL Queues
Using Magento 2.3 MySQL Queues
 
About elasticsearch
About elasticsearchAbout elasticsearch
About elasticsearch
 
Java script
Java scriptJava script
Java script
 
Java Design Patterns Tutorial | Edureka
Java Design Patterns Tutorial | EdurekaJava Design Patterns Tutorial | Edureka
Java Design Patterns Tutorial | Edureka
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
 
Developing an ASP.NET Web Application
Developing an ASP.NET Web ApplicationDeveloping an ASP.NET Web Application
Developing an ASP.NET Web Application
 
Bombardier adobe aem msm implementation
Bombardier adobe aem msm implementationBombardier adobe aem msm implementation
Bombardier adobe aem msm implementation
 
PHP - Introduction to PHP AJAX
PHP -  Introduction to PHP AJAXPHP -  Introduction to PHP AJAX
PHP - Introduction to PHP AJAX
 

Similar to ServletConfig & ServletContext

SCWCD : The servlet container : CHAP : 4
SCWCD : The servlet container : CHAP : 4SCWCD : The servlet container : CHAP : 4
SCWCD : The servlet container : CHAP : 4Ben Abdallah Helmi
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technologyMinal Maniar
 
Advance java session 18
Advance java session 18Advance java session 18
Advance java session 18Smita B Kumar
 
Spring review_for Semester II of Year 4
Spring review_for Semester II of Year 4Spring review_for Semester II of Year 4
Spring review_for Semester II of Year 4than sare
 
Web Application Deployment
Web Application DeploymentWeb Application Deployment
Web Application Deploymentelliando dias
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 5...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 5... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 5...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 5...WebStackAcademy
 
servlet 2.5 & JSP 2.0
servlet 2.5 & JSP 2.0servlet 2.5 & JSP 2.0
servlet 2.5 & JSP 2.0megrhi haikel
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteTushar B Kute
 
Http Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responsesHttp Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responsesbharathiv53
 
Java Servlet
Java ServletJava Servlet
Java ServletYoga Raja
 
Integrating Servlets and JSP (The MVC Architecture)
Integrating Servlets and JSP  (The MVC Architecture)Integrating Servlets and JSP  (The MVC Architecture)
Integrating Servlets and JSP (The MVC Architecture)Amit Ranjan
 

Similar to ServletConfig & ServletContext (20)

SCWCD : The servlet container : CHAP : 4
SCWCD : The servlet container : CHAP : 4SCWCD : The servlet container : CHAP : 4
SCWCD : The servlet container : CHAP : 4
 
Lecture6
Lecture6Lecture6
Lecture6
 
Sel study notes
Sel study notesSel study notes
Sel study notes
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technology
 
Servlet Part 2
Servlet Part 2Servlet Part 2
Servlet Part 2
 
Advance java session 18
Advance java session 18Advance java session 18
Advance java session 18
 
Spring review_for Semester II of Year 4
Spring review_for Semester II of Year 4Spring review_for Semester II of Year 4
Spring review_for Semester II of Year 4
 
Web Application Deployment
Web Application DeploymentWeb Application Deployment
Web Application Deployment
 
Servlet session 9
Servlet   session 9Servlet   session 9
Servlet session 9
 
java
java java
java
 
Servlets
ServletsServlets
Servlets
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 5...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 5... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 5...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 5...
 
Servlet11
Servlet11Servlet11
Servlet11
 
Spring tutorial
Spring tutorialSpring tutorial
Spring tutorial
 
servlet 2.5 & JSP 2.0
servlet 2.5 & JSP 2.0servlet 2.5 & JSP 2.0
servlet 2.5 & JSP 2.0
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
 
Unit5 servlets
Unit5 servletsUnit5 servlets
Unit5 servlets
 
Http Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responsesHttp Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responses
 
Java Servlet
Java ServletJava Servlet
Java Servlet
 
Integrating Servlets and JSP (The MVC Architecture)
Integrating Servlets and JSP  (The MVC Architecture)Integrating Servlets and JSP  (The MVC Architecture)
Integrating Servlets and JSP (The MVC Architecture)
 

Recently uploaded

18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
MICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxMICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxabhijeetpadhi001
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxUnboundStockton
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 

Recently uploaded (20)

18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
MICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxMICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptx
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docx
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 

ServletConfig & ServletContext

  • 1. ServletConfig & ServletContext :- ß Suppose let us here we have multiple servlet. Here there are three servlet A, B, C under classes’ folder. If you want to give any input to all the servlet A, B, C servlet. ß I want to pass the same connection object to AServlet , BServlet, CServlet. Suppose I have a JDBC connection object, I want to give that object to AServlet, BServlet, CServlet. ß I have only one resource I want to share that resource to all servlet then what should will do- it makes as. ASHUTOSH TRIVEDI Email:trivedi.ashutosh2013@gmail.com MNO—9580074408 Read ServletConfig & ServletContext by ASHUTOSH
  • 2. ß I have a single resource if I want to share same resource to all the user then resource need to become to public resource. ß 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. ß It is one per web application. So it is called as the global memory of web application. ß ServletContext object means it is the object of a java class (container supplier) implementing javax.servlet.ServletConext interface. ß Servlet container creates this object either during deployment of the web application or during server start-up. ß Servlet container destroys this object automatically when web application is undeployed or reloaded or stopped or when server is stopped/ re-started. ¸ An object of ServletContext is created by the web container at the time of deploying the project. ¸ There is only one ServletContext object per web application. ¸ This Servletcontext object can be used to get configuration information from web.xml file. If any information is shared to many object, it is better to provide it from the web.xml file using the <context-param> element.
  • 3. ¸ Easy to maintain if any information is shared to all the servlet it is better to make it available for all the servlet. We provide this information from the web.xml, so if the information is changer we don't need to modify the servlet. Thus if removes maintenance problem. ¸ Every web Application runs in a separate context which isolates it from another application running in the same server. ¸ Defines a set of methods that a servlet uses to communicate with its servlet container, for example to get the MIME type of a file dispatch requests or write to a log file.
  • 4. ¸ For every Servlet, web container will create one ServletConfig object to maintain Servlet level initialization parameter. By using this object Servlet can get its configuration information. ¸ Similarly for every web-application webcontainer creates one ServletContext object to maintain application level configuration information. ¸ Servlet can get application level configuration information through this context object only. ¸ ServletConfig per Servlet, whereas ServletContext per Web-application. ¸ If initialization parameters are common for all Servlets then it is not recommended to declare those parameters at Servlet level , we have to declare such type of parameters at application -level by using < context-param > <web-app> <context-param> <param-name>username</param-name> <param-value>scott</param-value> </context-param> </web-app> ¸ We can declare any number of context parameters but one < context-param > for each Servlet. ¸ < context-param > is the direct child tag of <web-app > & hence we can declare anywhere within <web-app> ¸ The context initialization parameters are available throughout the web-application anywhere. ¸ If we want to use same init-parameters then we can declare at context-level as <context-param> <param-name>username</param-name> <param-value>scott</param-value> </context-param>
  • 5. ¸ Within the Servlet we can access these context initialization parameters by using ServletContext object. How to Get ServletContext Object into Our Servlet Class ∑ In servlet programming we have 3 approaches for obtaining an object of ServletContext interface. Way 1. Syntax- //We can get ServletContext object from ServletConfig ServletConfig conf = getServletConfig(); ServletContext context = conf.getServletContext(); ∑ First obtain an object of ServletConfig interface ServletConfig interface contain direct method to get Context object, getServletContext();. Way 2. ∑ Direct approach, just call getServletContext() method available in GenericServlet [pre-defined]. In general we are extending our class with HttpServlet, but we know HttpServlet is the sub class of GenericServlet. Syntax- //Another convenient way to get ServletContext object ServletContext context = getServletContext(); Way 3. ∑ We can get the object of ServletContext by making use of HttpServletRequest object, we have direct method in HttpServletRequest interface. Syntax:- public class MyJava extends HttpServlet { public void doGet/doPost(HttpServletRequest req,-) { ServletContext ctx = req.getServletContext(); } }
  • 6. Commonly used methods of ServletContext interface There is given some commonly used methods of ServletContext interface. 1. public String getInitParameter(String name):Returns the parameter value for the specified parameter name. 2. public Enumeration getInitParameterNames():Returns the names of the context's initialization parameters. 3. public void setAttribute(String name,Object object):sets the given object in the application scope. 4. public Object getAttribute(String name):Returns the attribute for the specified name. 5. public Enumeration getInitParameterNames():Returns the names of the context's initialization parameters as an Enumeration of String objects. 6. public void removeAttribute(String name):Removes the attribute with the given name from the servlet context. Syntax to provide the initialization parameter in Context scope ∑ The context-param element, subelement of web-app, is used to define the initialization parameter in the application scope. The param-name and param-value are the sub- elements of the context-param. The param-name element defines parameter name and and param-value defines its value. web.xml <web-app> .... <context-param> <param-name>parametername</param-name> <param-value>parametervalue</param-value> </context-param> ... </web-app>
  • 7. Example of ServletContext to get the initialization parameter ∑ In this example, we are getting the initialization parameter from the web.xml file and printing the value of the initialization parameter. Notice that the object of ServletContext represents the application scope. So if we change the value of the parameter from the web.xml file, all the servlet classes will get the changed value. So we don't need to modify the servlet. So it is better to have the common information for most of the servlets in the web.xml file by context-param element. Let's see the simple example: web.xml <web-app> .... <display-name> HelloGenericServlet </display-name> <description> This is a simple web application with a source code . </description> <context-param> <param-name>drivername</param-name> <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value> </context-param> <context-param> <param-name>username</param-name> <param-value>system</param-value> </context-param> <context-param> <param-name>password</param-name> <param-value>oracle</param-value> </context-param> <servlet> <servlet-name> context </servlet-name> <servlet-class> ServletContextDemoServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name> context</servlet-name> <url-pattern> /context </url-pattern> </servlet-mapping> ...
  • 8. import java.io.*; import javax.servlet.*; public class ServletContextDemoServlet implements HttpServlet{ private static final long serialVersionUID=11; ServletConfig config=null; public void init() throws ServletException { System.out.println("-----------------------------------------------------------------"); System.out.println("init method is called in "+ this.getClass().getName()); System.out.println("-----------------------------------------------------------------"); } public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException{ res.setContentType("text/html"); PrintWriter out=res.getWriter(); ServletContext context=getServletContext(); out.print("<b> Read specific InitParam using context.getInitParameter(String paramName </b> <br> <br>"); String driverName=context.getInitParameter("drivername"); out.print(driverName+"<br><br>") out.print("<b> Read All InitParameters using getInitParameterNames() method </b> <br>"); Enumeration<String> initParamNamesEnum=context.getInitParameterNames(); String paramName=""; while (initParamNamesEnum.hasMoreElements()) { paramName = initParamNamesEnum.nextElement(); paramValue= context.getInitParameter(paramName); out.print("<br> "+ paramName + ": " + paramValue); } System.out.println("-----------------------------------------------------------------"); System.out.println("sevice method has been called "); System.out.println("-----------------------------------------------------------------"); res.setContentType("text/html");
  • 9. PrintWriter out=res.getWriter(); out.print("<html><body>"); out.print("<b>hello generic servlet</b>"); out.print ("<br>"); out.print("</body></html>"); } public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException { doGet(request, response) } public void destroy() { System.out.println("-----------------------------------------------------------------"); System.out.println("destroy method has been called and servlet is destroyed "); System.out.println("-----------------------------------------------------------------"); } } // Index.html <html> <head><title>Context test</title> <body> <li><a href="context">Context Test</a></li> </body> </html>
  • 10. ServletConfig (one per SERVLET): ¸ ServletConfig is an interface which is present in javax.servlet.* package. ¸ The purpose of ServletConfig is to pass some initial parameter values, technical information (driver name, database name, data source name, etc.) to a servlet. ¸ An object of ServletConfig will be created one per servlet. ¸ An object of ServletConfig will be created by the server at the time of executing public void init (ServletConfig) method. ¸ An object of ServletConfig cannot be accessed in the default constructor of a Servlet class.Since, at the time of executing default constructor ServletConfig object does not exist. ¸ By default ServletConfig object can be accessed with in init () method only but not in doGet and doPost. In order to use, in the entire servlet preserve the reference of ServletConfig into another variable and declare this variable into a Servlet class as a data member of ServletConfig.
  • 11. v When we want to give some global data to a servlet we must obtain an object of ServletConfig. v web.xml entries for ServletConfig <servlet> …………. <init-param> <param-name>Name of the parameter</param-name> <param-value>Value of the parameter</param-value> </init-param> …………. </servlet> For example: <servlet> <servlet-name>abc</servlet-name> <servlet-class>serv1</servlet-class> <init-param> <param-name>v1</param-name> <param-value>10</param-value> </init-param> <init-param> <param name>v2</param name>
  • 12. <param-value>20</param-value> </init-param> </servlet> ÿ The data which is available in ServletConfig object is in the form of (key, vlaue) OBTAINING an object of ServletConfig: v An object of ServletConfig can be obtained in two ways, they are by calling getServletConfig() method and by calling init (ServletConfig). v Within the Servlet we can get its Config object as follows. ServletConfig config=getServletConfig(); By calling getServletConfig () method: v getServletConfig() is the method which is available in javax.servlet.Servlet interface. This method is further inherited and defined into a class called javax.servlet.GenericServlet and that method is further inherited into another predefined class called javax.servlet.http.HttpServlet and it can be inherited into our own servlet class. For example: public class serv1 extends HttpServlet { public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { ………… ………… ServletConfig config=this.getServletConfig (); ………… ………… } }
  • 13. In the above example an object config contains (key, value) pair data of web.xml file which are written under <init-param> tag of <servlet> tag. v By calling init (ServletConfig): For example: public class serv2 extends HttpServlet { ServletConfig sc; public void init (ServletConfig sc) { Super.init (sc); // used for calling init (ServletConfig) method of HttpServlet this.sc=sc; // ServletConfig object sc is referenced } ………… ………… }; RETRIEVING DATA from ServletConfig interface object: ∑ In order to get the data from ServletConfig interface object we must use the following methods: public String getInitParameter (String); ____________ 1 public Enumeration getInitParameterNames (); ________ 2 v Method-1 is used for obtaining the parameter value by passing parameter name Key Value V1 10 V2 20 V3 30 Parameter-name Parameter-value
  • 14. String val1=config.getInitParameter (“v1”); String val2=config.getInitParameter (“v2”); String val3=config.getInitParameter (“v3”); vMethod-2 is used for obtaining all parameter names and their corresponding parameter values. For example: Enumeration en=config.getInitParameterNames (); while (en.hasMoreElements ()) { Object obj=en.nextElement (); String pname= (String) obj; String pvalue=config.getInitParameter (pname); out.println (pvalue+” is the value of ”+pname); } Serv1.java: import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; public class Serv1 extends HttpServlet { public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType ("text/html"); PrintWriter pw=res.getWriter (); ServletConfig config=getServletConfig (); String val1=config.getInitParameter ("v1"); String val2=config.getInitParameter ("v2"); String val3=config.getInitParameter ("v3"); String val4=config.getInitParameter ("v4"); pw.println ("<h3> Value of v1 is "+val1+"</h3>"); pw.println ("<h3> Value of v2 is "+val2+"</h3>"); pw.println ("<h3> Value of v3 is "+val3+"</h3>"); pw.println ("<h3> Value of v4 is "+val4+"</h3>"); } };
  • 15. Serv2.java: import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; public class Serv2 extends HttpServlet { public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType ("text/html"); PrintWriter pw=res.getWriter (); ServletConfig config=getServletConfig (); Enumeration en=config.getInitParameterNames (); while (en.hasMoreElements ()) { Object obj=en.nextElement (); String pname= (String) obj; String pvalue=config.getInitParameter (pname); pw.println ("</h2>"+pvalue+" is the value of "+pname+"</h2>"); } } } web.xml: <web-app> <servlet> <servlet-name>abc</servlet-name> <servlet-class>Serv1</servlet-class> <init-param> <param-name>v1</param-name> <param-value>10</param-value> </init-param> <init-param> <param-name>v2</param-name> <param-value>20</param-value> </init-param> </servlet> <servlet> <servlet-name>pqr</servlet-name> <servlet-class>Serv2</servlet-class>
  • 16. <init-param> <param-name>v3</param-name> <param-value>30</param-value> </init-param> <init-param> <param-name>v4</param-name> <param-value>40</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>abc</servlet-name> <url-pattern>/firstserv</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>pqr</servlet-name> <url-pattern>/secondserv</url-pattern> </servlet-mapping> </web-app> v Develop a flexible servlet that should display the data of the database irrespective driver name, tablename and dsn name? Answer: DbServ.java: import javax.servlet.*; import javax.servlet.http.*; import java.sql.*; import java.io.*; public class DbServ extends HttpServlet { ServletConfig sc=null; public void init (ServletConfig sc) throws ServletException { super.init (sc); this.sc=sc; } public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType ("text/html"); PrintWriter pw=res.getWriter (); String dname=sc.getInitParameter ("dname"); String url=sc.getInitParameter ("url"); String tab=sc.getInitParameter ("tab");
  • 17. try { Class.forName (dname); Connection con=DriverManager.getConnection (url,"scott","tiger"); Statement st=con.createStatement (); ResultSet rs=st.executeQuery ("select * from "+tab); while (rs.next ()) { pw.println ("<h2>"+rs.getString (1)+""+rs.getString (2)+""+rs.getString (3)+"</h2>"); } con.close (); } catch (Exception e) { res.sendError (503,"PROBLEM IN DATABASE..."); } } }; web.xml: <web-app> <servlet> <servlet-name>abc</servlet-name> <servlet-class>DbServ</servlet-class> <init-param> <param-name>dname</param-name> <param-value>oracle.jdbc.driver.OracleDriver ()</param-value> </init-param> <init-param> <param-name>url</param-name> <param-value>jdbc:oracle:thin:@localhost:1521:xe</param-value> </init-param> <init-param> <param-name>tab</param-name> <param-value>emp</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>abc</servlet-name> <url-pattern>/dbdata</url-pattern> </servlet-mapping> </web-app>
  • 18. Property Servlet init-param Servlet context-param 1. declaration By using init-param with in servlet. <servlet> <init-param> <param-name> <param-value> </init-param> </servlet> By using init-param with in web-app. <servlet> <context-param> <param-name> <param-value> </context-param> </servlet> 2. Servlet code to Access the parameter String value=getInitParameter("pname") ; (or) String value=getServletConfig( ).getInitParameter("pname"); String value=getServletContext( ).getInitParameter("pname") ; (or) String value=getServletConfig( ).getServletContext( ).getInitParameter("pname") ; 3. Availability(Scope) Available only for a particular Servlet in which <init-param> is declared. Available for all Servlet's & Jsp's within the web- application.