SlideShare una empresa de Scribd logo
1 de 18
Descargar para leer sin conexión
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.

Más contenido relacionado

La actualidad más candente

PHP-MySQL Database Connectivity Using XAMPP Server
PHP-MySQL Database Connectivity Using XAMPP ServerPHP-MySQL Database Connectivity Using XAMPP Server
PHP-MySQL Database Connectivity Using XAMPP ServerRajiv Bhatia
 
Threads And Synchronization in C#
Threads And Synchronization in C#Threads And Synchronization in C#
Threads And Synchronization in C#Rizwan Ali
 
AEM (CQ) Dispatcher Security and CDN+Browser Caching
AEM (CQ) Dispatcher Security and CDN+Browser CachingAEM (CQ) Dispatcher Security and CDN+Browser Caching
AEM (CQ) Dispatcher Security and CDN+Browser CachingAndrew Khoury
 
Android activity
Android activityAndroid activity
Android activityKrazy Koder
 
Angular Best Practices - Perfomatix
Angular Best Practices - PerfomatixAngular Best Practices - Perfomatix
Angular Best Practices - PerfomatixPerfomatix Solutions
 
C++ Memory Management
C++ Memory ManagementC++ Memory Management
C++ Memory ManagementRahul Jamwal
 
Introduction to CSS
Introduction to CSSIntroduction to CSS
Introduction to CSSAmit Tyagi
 
Sqlite
SqliteSqlite
SqliteKumar
 
React state
React  stateReact  state
React stateDucat
 
Shared preferences
Shared preferencesShared preferences
Shared preferencesSourabh Sahu
 
React-JS Component Life-cycle Methods
React-JS Component Life-cycle MethodsReact-JS Component Life-cycle Methods
React-JS Component Life-cycle MethodsANKUSH CHAVAN
 
Python unit 3 m.sc cs
Python unit 3 m.sc csPython unit 3 m.sc cs
Python unit 3 m.sc csKALAISELVI P
 
What Is Php
What Is PhpWhat Is Php
What Is PhpAVC
 

La actualidad más candente (20)

PHP-MySQL Database Connectivity Using XAMPP Server
PHP-MySQL Database Connectivity Using XAMPP ServerPHP-MySQL Database Connectivity Using XAMPP Server
PHP-MySQL Database Connectivity Using XAMPP Server
 
Threads And Synchronization in C#
Threads And Synchronization in C#Threads And Synchronization in C#
Threads And Synchronization in C#
 
Spring beans
Spring beansSpring beans
Spring beans
 
AEM (CQ) Dispatcher Security and CDN+Browser Caching
AEM (CQ) Dispatcher Security and CDN+Browser CachingAEM (CQ) Dispatcher Security and CDN+Browser Caching
AEM (CQ) Dispatcher Security and CDN+Browser Caching
 
Java servlets
Java servletsJava servlets
Java servlets
 
Android activity
Android activityAndroid activity
Android activity
 
Angular Best Practices - Perfomatix
Angular Best Practices - PerfomatixAngular Best Practices - Perfomatix
Angular Best Practices - Perfomatix
 
C++ Memory Management
C++ Memory ManagementC++ Memory Management
C++ Memory Management
 
JAVA AWT
JAVA AWTJAVA AWT
JAVA AWT
 
Introduction to CSS
Introduction to CSSIntroduction to CSS
Introduction to CSS
 
Sqlite
SqliteSqlite
Sqlite
 
Web api
Web apiWeb api
Web api
 
React state
React  stateReact  state
React state
 
Broadcast Receiver
Broadcast ReceiverBroadcast Receiver
Broadcast Receiver
 
SQLITE Android
SQLITE AndroidSQLITE Android
SQLITE Android
 
Shared preferences
Shared preferencesShared preferences
Shared preferences
 
React-JS Component Life-cycle Methods
React-JS Component Life-cycle MethodsReact-JS Component Life-cycle Methods
React-JS Component Life-cycle Methods
 
Local storage
Local storageLocal storage
Local storage
 
Python unit 3 m.sc cs
Python unit 3 m.sc csPython unit 3 m.sc cs
Python unit 3 m.sc cs
 
What Is Php
What Is PhpWhat Is Php
What Is Php
 

Similar a 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 a 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)
 

Último

Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseAnaAcapella
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxAmanpreet Kaur
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxcallscotland1987
 

Último (20)

Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 

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.