SlideShare a Scribd company logo
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 Servlets
Java ServletsJava Servlets
Java Servlets
BG Java EE Course
 
Event handling
Event handlingEvent handling
Event handling
Anand Grewal
 
Java swing
Java swingJava swing
Java swing
Apurbo Datta
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHP
Taha Malampatti
 
Spring boot
Spring bootSpring boot
Spring boot
sdeeg
 
Java Applet
Java AppletJava Applet
Command line arguments.21
Command line arguments.21Command line arguments.21
Command line arguments.21
myrajendra
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
Jeevesh Pandey
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
Scott Leberknight
 
Java applets
Java appletsJava applets
Java applets
lopjuan
 
Android intents
Android intentsAndroid intents
Android intents
Siva Ramakrishna kv
 
Python Dictionaries and Sets
Python Dictionaries and SetsPython Dictionaries and Sets
Python Dictionaries and Sets
Nicole Ryan
 
Applets
AppletsApplets
Applets
SanthiNivas
 
Procedures functions structures in VB.Net
Procedures  functions  structures in VB.NetProcedures  functions  structures in VB.Net
Procedures functions structures in VB.Net
tjunicornfx
 
Fragment
Fragment Fragment
Operators in java
Operators in javaOperators in java
Operators in java
Then Murugeshwari
 
Windowforms controls c#
Windowforms controls c#Windowforms controls c#
Windowforms controls c#
prabhu rajendran
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
 
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesSpring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Hitesh-Java
 
String Handling
String HandlingString Handling
String Handling
Bharat17485
 

What's hot (20)

Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Event handling
Event handlingEvent handling
Event handling
 
Java swing
Java swingJava swing
Java swing
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHP
 
Spring boot
Spring bootSpring boot
Spring boot
 
Java Applet
Java AppletJava Applet
Java Applet
 
Command line arguments.21
Command line arguments.21Command line arguments.21
Command line arguments.21
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Java applets
Java appletsJava applets
Java applets
 
Android intents
Android intentsAndroid intents
Android intents
 
Python Dictionaries and Sets
Python Dictionaries and SetsPython Dictionaries and Sets
Python Dictionaries and Sets
 
Applets
AppletsApplets
Applets
 
Procedures functions structures in VB.Net
Procedures  functions  structures in VB.NetProcedures  functions  structures in VB.Net
Procedures functions structures in VB.Net
 
Fragment
Fragment Fragment
Fragment
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Windowforms controls c#
Windowforms controls c#Windowforms controls c#
Windowforms controls c#
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
 
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesSpring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
 
String Handling
String HandlingString Handling
String Handling
 

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 : 4
Ben Abdallah Helmi
 
Lecture6
Lecture6Lecture6
Sel study notes
Sel study notesSel study notes
Sel study notes
Lalit Singh
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technology
Minal Maniar
 
Servlet Part 2
Servlet Part 2Servlet Part 2
Servlet Part 2
vikram singh
 
Advance java session 18
Advance java session 18Advance java session 18
Advance java session 18
Smita 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 4
than sare
 
Web Application Deployment
Web Application DeploymentWeb Application Deployment
Web Application Deployment
elliando dias
 
Servlet session 9
Servlet   session 9Servlet   session 9
Servlet session 9
Anuj Singh Rajput
 
java
java java
Servlets
ServletsServlets
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
 
Servlet11
Servlet11Servlet11
Servlet11
patinijava
 
Spring tutorial
Spring tutorialSpring tutorial
Spring tutorial
Sanjoy Kumer Deb
 
servlet 2.5 & JSP 2.0
servlet 2.5 & JSP 2.0servlet 2.5 & JSP 2.0
servlet 2.5 & JSP 2.0
megrhi 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 Kute
Tushar B Kute
 
Unit5 servlets
Unit5 servletsUnit5 servlets
Unit5 servlets
Praveen Yadav
 
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
bharathiv53
 
Java Servlet
Java ServletJava Servlet
Java Servlet
Yoga 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

South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
Academy of Science of South Africa
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Excellence Foundation for South Sudan
 
Types of Herbal Cosmetics its standardization.
Types of Herbal Cosmetics its standardization.Types of Herbal Cosmetics its standardization.
Types of Herbal Cosmetics its standardization.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
AyyanKhan40
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
TechSoup
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
Jean Carlos Nunes Paixão
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
amberjdewit93
 
Top five deadliest dog breeds in America
Top five deadliest dog breeds in AmericaTop five deadliest dog breeds in America
Top five deadliest dog breeds in America
Bisnar Chase Personal Injury Attorneys
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
heathfieldcps1
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
Celine George
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
Priyankaranawat4
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
ak6969907
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
Celine George
 
Life upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for studentLife upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for student
NgcHiNguyn25
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Akanksha trivedi rama nursing college kanpur.
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
adhitya5119
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
chanes7
 

Recently uploaded (20)

South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
 
Types of Herbal Cosmetics its standardization.
Types of Herbal Cosmetics its standardization.Types of Herbal Cosmetics its standardization.
Types of Herbal Cosmetics its standardization.
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
 
Top five deadliest dog breeds in America
Top five deadliest dog breeds in AmericaTop five deadliest dog breeds in America
Top five deadliest dog breeds in America
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
 
Life upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for studentLife upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for student
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
 

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.