SlideShare a Scribd company logo
Servlet
Servlet Hierarchy
The container initialzes the servlet by loading the class invoking the servlet’s no-args constructor and invoking servlet’s init() method.  The init() method which the servlet’s calls is called only once in the servlet’s life and always before the servlet can service the request of the client. The init() method gives theaccess to the ServletConfig and ServletContext objects, which the servlet needs to get the information about the servlet configuration and web=app. The container ends the servlet’s life by calling destroy method. Most of the servlet’s life is spent in servlet’s service method. Every request to the servlet runs in the separate thread. There is only one instance of any particular thraed. Your servlet always extends javxServlet.http.HttpServlet from which it inherits an implementation of service() method that takes HttpServletResponse and HttpServlatRequest HttpSErvlet extends the javax servlet.GenericServlet – an abstract class that implements most of the servlet method. Generic Servlet implements the servlet interface. Servlet class are in 2 packages javax.servlet and javax.servlet.http; You can override Servlet’s init() method or one of the service() method (doGet() or doPost()).
Servlet Configuration Sometimes it is necessary to provide initial configuration information for Servlets. Configuration information for a Servlet may consist of a string or a set of string values included in the Servlet’s web.xml declaration. This functionality allows a Servlet to have initial parameters specified outside of the compiled code and changed without needing to recompile the Servlet. Each servlet has an object associated with it called the ServletConfig19. This object is created by the container and implements the javax.servlet. ServletConfig   interface . It is the ServletConfig that contains the initialization parameters. A reference to this object can be retrieved by calling the  getServletConfig()  method. The ServletConfig object provides the following methods for accessing initial parameters: getInitParameter(String name) The getInitParameter() returns a String object that contains the value of the named initialization parameter or null if the parameter does not exist. getInitParameterNames() The getInitParameterNames() method returns the names of the Servlet’s initialization parameters as an Enumeration of String objects or an empty Enumeration if the Servlet has no initialization parameters.
Defining initial parameters for a Servlet requires using the init-param, param-name, and param-value elements in web.xml. Each init-param element defines one initial parameter and must contain a parameter name and value specified by children param-name and param-value elements, respectively. A Servlet may have as many initial parameters as needed, and initial parameter information for a specific Servlet should be specified within the servlet element for that particular Servlet. Eg: import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class InternationalizedHelloWorld extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType(&quot;text/html&quot;); PrintWriter out = response.getWriter(); out.println(&quot;<html>&quot;); out.println(&quot;<head>&quot;); String greeting;
greeting = getServletConfig().getInitParameter(&quot;greeting&quot;); out.println(&quot;<title>&quot; +greeting+&quot;</title>&quot;); out.println(&quot;</head>&quot;); out.println(&quot;<body>&quot;); out.println(&quot;<h1>&quot; +greeting+&quot;</h1>&quot;); out.println(&quot;</body>&quot;); out.println(&quot;</html>&quot;); } } Open up web.xml in the /WEB-INF folder of the jspbook Web Application and add in a declaration and mapping to /InternationalizedHelloWorld for the InternationalizedHelloWorld Servlet. <servlet> <servlet-name>InternationalizedHelloWorld</servlet-name> <servlet-class> com.jspbook.InternationalizedHelloWorld </servlet-class> <init-param> <param-name>greeting</param-name> <param-value>Bonjour!</param-value> </init-param> </servlet> ...
Limitations of Configuration Initial parameters are a good method of providing simple one-string values that Servlets can use to configure themselves. This approach is simple and effective, but is a limited method of configuring a Servlet. For more complex Servlets it is not uncommon to see a completely separate configuration file created to accompany web.xml.When developing Servlets, keep in mind that nothing stops you from doing this. If the parameter name and parameter values mappings are not adequate, do not use them! Client/Server Servlet Programming A Servlet request and response is represented by the javax.servlet.Servlet Request and javax.servlet.ServletResponse objects, or a corresponding subclass of them. For HTTP Servlets the corresponding classes are HttpServlet Request and HttpServletResponse HttpServletResponse The first and perhaps most important functionality to discuss is how to send information back to a client. As its name implies, the HttpServletResponse object is responsible for this functionality.
By itself the HttpServletResponse object only produces an empty HTTP response. Sending back custom content requires using either the getWriter() or getOutputStream() method to obtain an output stream for writing content. These two methods return suitable objects for sending either text or binary content to a client, respectively. Only one of the two methods may be used with a given HttpServletResponse object. Attempting to call both methods causes an exception to be thrown. With the HelloWorld Servlet example, the getWriter() method was used to get an output stream for sending the HTML markup. In the first few lines of HelloWorld.java, a getWriter() call obtained a java.io.PrintWriter object suitable for sending back the text. PrintWriter out = response.getWriter(); out.println(&quot;<html>&quot;); out.println(&quot;<head>&quot;); out.println(&quot;<title>Hello World!</title>&quot;); Response Redirection The sendRedirect() method takes one parameter, a string representing the new URL, and automatically sets the HTTP 302 status code with appropriate headers. Using the sendRedirect() method and a java.util. Hashtable, it is easy to create a Servlet for tracking link
PrintWriter out = response.getWriter(); String name=request.getParameter(&quot;t1&quot;); String age=request.getParameter(&quot;t2&quot;); if(name.equals(&quot;&quot;) || age.equals(&quot;&quot;)){ response.sendRedirect(&quot;index.html&quot;); } HttpServletRequest A client’s HTTP request is represented by an HttpServletRequest object. The HttpServletRequest object is primarily used for getting request headers, parameters, and files or data sent by a client. However, the Servlet specification enhances this object to also interact with a Web Application. Request Delegation and Request Scope Request delegation is a powerful feature of the Servlet API. A single client’s request can pass through many Servlets and/or to any other resource in the Web Application. The entire process is done completely on the server-side and, unlike response redirection, does not require any action from a client or extra information sent between the client and server. Request delegation is available through the javax.servlet.RequestDispatcher object. An appropriate instance of a RequestDispatcher object is available by calling either of the following methods of a ServletRequest object:
getRequestDispatcher(java.lang.String path):  The getRequestDispatcher() method returns the RequestDispatcher object for a given path. The path value may lead to any resource in the Web Application and must start from the base directory, “/”. . •  forward(javax.servlet.ServletRequest, javax.servlet.ServletResponse):  The forward() method delegates a request and response to the resource of the RequestDispatcher object. A call to the forward() method may be used only if no content has been previously sent to a client. No further data can be sent to the client after the forward has completed. •  include(javax.servlet.ServletRequest, javax.servlet.ServletResponse):  The include() method works similarly to forward() but has some restrictions. A Servlet can include() any number of resources that can each generate responses, but the resource is not allowed to set headers or commit a response.
Request Dispatcher Ex if(name.equals(&quot;&quot;) || age.equals(&quot;&quot;)){ RequestDispatcher rd=request.getRequestDispatcher(&quot;AnotherServlet&quot;); rd.forward(request,response); return; } Here if name and age are equal to null then control will get passed to another servlet which perform further processing.
ServletContext The javax.servlet.ServletContext interface represents a Servlet’s view of the Web Application it belongs to. Through the ServletContext interface, a Servlet can access raw input streams to Web Application resources, virtual directory translation, a common mechanism for logging information, and an  application scope  for binding objects. Individual container vendors provide specific implementations of ServletContext objects, but they all provide the same functionality defined by the ServletContext interface. A ServletContext object implements similar getInitParam() and getInitParamNames() methods demonstrated for ServletConfig. The difference is that these methods do not access initial parameters for a particular Servlet, but rather parameters specified for the entire Web Application. <web-app> <context-param> <param-name>admin email</param-name> <param-value>admin@jspbook.com</param-value> </context-param> <servlet> <servlet-name>helloworld</servlet-name> <servlet-class>com.jspbook.HelloWorld</servlet-class>
response.setContentType(&quot;text/html&quot;); PrintWriter out = response.getWriter(); out.println(&quot;<html>&quot;); out.println(&quot;<head>&quot;); out.println(&quot;<title>An Error Has Occurred!</title>&quot;); out.println(&quot;</head>&quot;); out.println(&quot;<body>&quot;); ServletContext sc = getServletConfig().getServletContext(); String adminEmail = sc.getInitParameter(&quot;admin email&quot;); out.println(&quot;<h1>Error Page</h1>&quot;); out.print(&quot;Sorry! An unexpected error has occurred.&quot;); out.print(&quot;Please send an error report to &quot;+adminEmail+&quot;.&quot;); out.println(&quot;</body>&quot;); out.println(&quot;</html>&quot;); } }

More Related Content

What's hot (20)

PDF
Java9 Beyond Modularity - Java 9 más allá de la modularidad
David Gómez García
 
PDF
Sun certifiedwebcomponentdeveloperstudyguide
Alberto Romero Jiménez
 
PPTX
Java servlets
yuvarani p
 
PDF
Protocol-Oriented Networking
Mostafa Amer
 
PPT
Java servlet life cycle - methods ppt
kamal kotecha
 
PPTX
Java script advance-auroskills (2)
BoneyGawande
 
PDF
ServletConfig & ServletContext
ASHUTOSH TRIVEDI
 
PPTX
SCWCD : The servlet container : CHAP : 4
Ben Abdallah Helmi
 
PPS
Java rmi example program with code
kamal kotecha
 
PDF
RMI (Remote Method Invocation)
Thesis Scientist Private Limited
 
PPT
Chap4 4 1
Hemo Chella
 
PDF
Bt0083 server side programing 2
Techglyphs
 
PPT
Testing Javascript with Jasmine
Tim Tyrrell
 
PPTX
Java Servlet
Yoga Raja
 
PDF
Leveraging Completable Futures to handle your query results Asynchrhonously
David Gómez García
 
PDF
Sane Sharding with Akka Cluster
miciek
 
PPTX
JSP- JAVA SERVER PAGES
Yoga Raja
 
PPTX
Full Stack Unit Testing
GlobalLogic Ukraine
 
PPS
Advance Java
Vidyacenter
 
Java9 Beyond Modularity - Java 9 más allá de la modularidad
David Gómez García
 
Sun certifiedwebcomponentdeveloperstudyguide
Alberto Romero Jiménez
 
Java servlets
yuvarani p
 
Protocol-Oriented Networking
Mostafa Amer
 
Java servlet life cycle - methods ppt
kamal kotecha
 
Java script advance-auroskills (2)
BoneyGawande
 
ServletConfig & ServletContext
ASHUTOSH TRIVEDI
 
SCWCD : The servlet container : CHAP : 4
Ben Abdallah Helmi
 
Java rmi example program with code
kamal kotecha
 
RMI (Remote Method Invocation)
Thesis Scientist Private Limited
 
Chap4 4 1
Hemo Chella
 
Bt0083 server side programing 2
Techglyphs
 
Testing Javascript with Jasmine
Tim Tyrrell
 
Java Servlet
Yoga Raja
 
Leveraging Completable Futures to handle your query results Asynchrhonously
David Gómez García
 
Sane Sharding with Akka Cluster
miciek
 
JSP- JAVA SERVER PAGES
Yoga Raja
 
Full Stack Unit Testing
GlobalLogic Ukraine
 
Advance Java
Vidyacenter
 

Similar to Servlet11 (20)

PPT
Java Servlets
BG Java EE Course
 
PPT
1 java servlets and jsp
Ankit Minocha
 
PPT
Servlets
Sasidhar Kothuru
 
PPT
JAVA Servlets
deepak kumar
 
PPTX
servlets sessions and cookies, jdbc connectivity
snehalatha790700
 
PPT
Servlets
Manav Prasad
 
ODP
Servlets
ramesh kumar
 
ODP
servlet 2.5 & JSP 2.0
megrhi haikel
 
PDF
Bt0083 server side programing
Techglyphs
 
PPTX
SERVLETS (2).pptxintroduction to servlet with all servlets
RadhikaP41
 
PDF
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Tushar B Kute
 
PPTX
Servlets
Rajkiran Mummadi
 
PPTX
JAVA SERVLETS acts as a middle layer between a request coming from a web brow...
ssuser4f7d71
 
PPTX
Integrating Servlets and JSP (The MVC Architecture)
Amit Ranjan
 
PPTX
Understanding JSP -Servlets
Gagandeep Singh
 
PDF
Servlets
Abdalla Mahmoud
 
PPTX
java Servlet technology
Tanmoy Barman
 
PPTX
21CS642 Module 4_1 Servlets PPT.pptx VI SEM CSE Students
VENKATESHBHAT25
 
PPS
Exploring the Java Servlet Technology
Riza Nurman
 
PPT
Servlet Part 2
vikram singh
 
Java Servlets
BG Java EE Course
 
1 java servlets and jsp
Ankit Minocha
 
JAVA Servlets
deepak kumar
 
servlets sessions and cookies, jdbc connectivity
snehalatha790700
 
Servlets
Manav Prasad
 
Servlets
ramesh kumar
 
servlet 2.5 & JSP 2.0
megrhi haikel
 
Bt0083 server side programing
Techglyphs
 
SERVLETS (2).pptxintroduction to servlet with all servlets
RadhikaP41
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Tushar B Kute
 
JAVA SERVLETS acts as a middle layer between a request coming from a web brow...
ssuser4f7d71
 
Integrating Servlets and JSP (The MVC Architecture)
Amit Ranjan
 
Understanding JSP -Servlets
Gagandeep Singh
 
Servlets
Abdalla Mahmoud
 
java Servlet technology
Tanmoy Barman
 
21CS642 Module 4_1 Servlets PPT.pptx VI SEM CSE Students
VENKATESHBHAT25
 
Exploring the Java Servlet Technology
Riza Nurman
 
Servlet Part 2
vikram singh
 
Ad

More from patinijava (18)

PPT
Web Services Part 2
patinijava
 
PPT
Web Services Part 1
patinijava
 
PPT
Struts N E W
patinijava
 
PPT
Session Management
patinijava
 
PPT
S E R V L E T S
patinijava
 
PPS
Struts Java I I Lecture 8
patinijava
 
PPT
Servlet Api
patinijava
 
PPT
Sping Slide 6
patinijava
 
PPT
Entity Manager
patinijava
 
PPT
Ejb6
patinijava
 
PPT
Ejb5
patinijava
 
PPT
Ejb4
patinijava
 
PPT
Patni Hibernate
patinijava
 
PPT
Spring Transaction
patinijava
 
PPT
Webbasics
patinijava
 
PPT
Internetbasics
patinijava
 
PPT
Jsp
patinijava
 
PPT
Portlet
patinijava
 
Web Services Part 2
patinijava
 
Web Services Part 1
patinijava
 
Struts N E W
patinijava
 
Session Management
patinijava
 
S E R V L E T S
patinijava
 
Struts Java I I Lecture 8
patinijava
 
Servlet Api
patinijava
 
Sping Slide 6
patinijava
 
Entity Manager
patinijava
 
Patni Hibernate
patinijava
 
Spring Transaction
patinijava
 
Webbasics
patinijava
 
Internetbasics
patinijava
 
Portlet
patinijava
 
Ad

Recently uploaded (20)

PPTX
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
PDF
Peak of Data & AI Encore - Real-Time Insights & Scalable Editing with ArcGIS
Safe Software
 
PDF
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
PPTX
AVL ( audio, visuals or led ), technology.
Rajeshwri Panchal
 
PDF
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
PDF
The Past, Present & Future of Kenya's Digital Transformation
Moses Kemibaro
 
PPTX
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
PPTX
Simple and concise overview about Quantum computing..pptx
mughal641
 
PPTX
Farrell_Programming Logic and Design slides_10e_ch02_PowerPoint.pptx
bashnahara11
 
PPTX
Agile Chennai 18-19 July 2025 | Workshop - Enhancing Agile Collaboration with...
AgileNetwork
 
PDF
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
PPTX
AI in Daily Life: How Artificial Intelligence Helps Us Every Day
vanshrpatil7
 
PDF
The Future of Artificial Intelligence (AI)
Mukul
 
PDF
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
PDF
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
PDF
How ETL Control Logic Keeps Your Pipelines Safe and Reliable.pdf
Stryv Solutions Pvt. Ltd.
 
PDF
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
PDF
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
PDF
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
PPTX
AI Code Generation Risks (Ramkumar Dilli, CIO, Myridius)
Priyanka Aash
 
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
Peak of Data & AI Encore - Real-Time Insights & Scalable Editing with ArcGIS
Safe Software
 
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
AVL ( audio, visuals or led ), technology.
Rajeshwri Panchal
 
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
The Past, Present & Future of Kenya's Digital Transformation
Moses Kemibaro
 
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
Simple and concise overview about Quantum computing..pptx
mughal641
 
Farrell_Programming Logic and Design slides_10e_ch02_PowerPoint.pptx
bashnahara11
 
Agile Chennai 18-19 July 2025 | Workshop - Enhancing Agile Collaboration with...
AgileNetwork
 
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
AI in Daily Life: How Artificial Intelligence Helps Us Every Day
vanshrpatil7
 
The Future of Artificial Intelligence (AI)
Mukul
 
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
How ETL Control Logic Keeps Your Pipelines Safe and Reliable.pdf
Stryv Solutions Pvt. Ltd.
 
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
AI Code Generation Risks (Ramkumar Dilli, CIO, Myridius)
Priyanka Aash
 

Servlet11

  • 3. The container initialzes the servlet by loading the class invoking the servlet’s no-args constructor and invoking servlet’s init() method. The init() method which the servlet’s calls is called only once in the servlet’s life and always before the servlet can service the request of the client. The init() method gives theaccess to the ServletConfig and ServletContext objects, which the servlet needs to get the information about the servlet configuration and web=app. The container ends the servlet’s life by calling destroy method. Most of the servlet’s life is spent in servlet’s service method. Every request to the servlet runs in the separate thread. There is only one instance of any particular thraed. Your servlet always extends javxServlet.http.HttpServlet from which it inherits an implementation of service() method that takes HttpServletResponse and HttpServlatRequest HttpSErvlet extends the javax servlet.GenericServlet – an abstract class that implements most of the servlet method. Generic Servlet implements the servlet interface. Servlet class are in 2 packages javax.servlet and javax.servlet.http; You can override Servlet’s init() method or one of the service() method (doGet() or doPost()).
  • 4. Servlet Configuration Sometimes it is necessary to provide initial configuration information for Servlets. Configuration information for a Servlet may consist of a string or a set of string values included in the Servlet’s web.xml declaration. This functionality allows a Servlet to have initial parameters specified outside of the compiled code and changed without needing to recompile the Servlet. Each servlet has an object associated with it called the ServletConfig19. This object is created by the container and implements the javax.servlet. ServletConfig interface . It is the ServletConfig that contains the initialization parameters. A reference to this object can be retrieved by calling the getServletConfig() method. The ServletConfig object provides the following methods for accessing initial parameters: getInitParameter(String name) The getInitParameter() returns a String object that contains the value of the named initialization parameter or null if the parameter does not exist. getInitParameterNames() The getInitParameterNames() method returns the names of the Servlet’s initialization parameters as an Enumeration of String objects or an empty Enumeration if the Servlet has no initialization parameters.
  • 5. Defining initial parameters for a Servlet requires using the init-param, param-name, and param-value elements in web.xml. Each init-param element defines one initial parameter and must contain a parameter name and value specified by children param-name and param-value elements, respectively. A Servlet may have as many initial parameters as needed, and initial parameter information for a specific Servlet should be specified within the servlet element for that particular Servlet. Eg: import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class InternationalizedHelloWorld extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType(&quot;text/html&quot;); PrintWriter out = response.getWriter(); out.println(&quot;<html>&quot;); out.println(&quot;<head>&quot;); String greeting;
  • 6. greeting = getServletConfig().getInitParameter(&quot;greeting&quot;); out.println(&quot;<title>&quot; +greeting+&quot;</title>&quot;); out.println(&quot;</head>&quot;); out.println(&quot;<body>&quot;); out.println(&quot;<h1>&quot; +greeting+&quot;</h1>&quot;); out.println(&quot;</body>&quot;); out.println(&quot;</html>&quot;); } } Open up web.xml in the /WEB-INF folder of the jspbook Web Application and add in a declaration and mapping to /InternationalizedHelloWorld for the InternationalizedHelloWorld Servlet. <servlet> <servlet-name>InternationalizedHelloWorld</servlet-name> <servlet-class> com.jspbook.InternationalizedHelloWorld </servlet-class> <init-param> <param-name>greeting</param-name> <param-value>Bonjour!</param-value> </init-param> </servlet> ...
  • 7. Limitations of Configuration Initial parameters are a good method of providing simple one-string values that Servlets can use to configure themselves. This approach is simple and effective, but is a limited method of configuring a Servlet. For more complex Servlets it is not uncommon to see a completely separate configuration file created to accompany web.xml.When developing Servlets, keep in mind that nothing stops you from doing this. If the parameter name and parameter values mappings are not adequate, do not use them! Client/Server Servlet Programming A Servlet request and response is represented by the javax.servlet.Servlet Request and javax.servlet.ServletResponse objects, or a corresponding subclass of them. For HTTP Servlets the corresponding classes are HttpServlet Request and HttpServletResponse HttpServletResponse The first and perhaps most important functionality to discuss is how to send information back to a client. As its name implies, the HttpServletResponse object is responsible for this functionality.
  • 8. By itself the HttpServletResponse object only produces an empty HTTP response. Sending back custom content requires using either the getWriter() or getOutputStream() method to obtain an output stream for writing content. These two methods return suitable objects for sending either text or binary content to a client, respectively. Only one of the two methods may be used with a given HttpServletResponse object. Attempting to call both methods causes an exception to be thrown. With the HelloWorld Servlet example, the getWriter() method was used to get an output stream for sending the HTML markup. In the first few lines of HelloWorld.java, a getWriter() call obtained a java.io.PrintWriter object suitable for sending back the text. PrintWriter out = response.getWriter(); out.println(&quot;<html>&quot;); out.println(&quot;<head>&quot;); out.println(&quot;<title>Hello World!</title>&quot;); Response Redirection The sendRedirect() method takes one parameter, a string representing the new URL, and automatically sets the HTTP 302 status code with appropriate headers. Using the sendRedirect() method and a java.util. Hashtable, it is easy to create a Servlet for tracking link
  • 9. PrintWriter out = response.getWriter(); String name=request.getParameter(&quot;t1&quot;); String age=request.getParameter(&quot;t2&quot;); if(name.equals(&quot;&quot;) || age.equals(&quot;&quot;)){ response.sendRedirect(&quot;index.html&quot;); } HttpServletRequest A client’s HTTP request is represented by an HttpServletRequest object. The HttpServletRequest object is primarily used for getting request headers, parameters, and files or data sent by a client. However, the Servlet specification enhances this object to also interact with a Web Application. Request Delegation and Request Scope Request delegation is a powerful feature of the Servlet API. A single client’s request can pass through many Servlets and/or to any other resource in the Web Application. The entire process is done completely on the server-side and, unlike response redirection, does not require any action from a client or extra information sent between the client and server. Request delegation is available through the javax.servlet.RequestDispatcher object. An appropriate instance of a RequestDispatcher object is available by calling either of the following methods of a ServletRequest object:
  • 10. getRequestDispatcher(java.lang.String path): The getRequestDispatcher() method returns the RequestDispatcher object for a given path. The path value may lead to any resource in the Web Application and must start from the base directory, “/”. . • forward(javax.servlet.ServletRequest, javax.servlet.ServletResponse): The forward() method delegates a request and response to the resource of the RequestDispatcher object. A call to the forward() method may be used only if no content has been previously sent to a client. No further data can be sent to the client after the forward has completed. • include(javax.servlet.ServletRequest, javax.servlet.ServletResponse): The include() method works similarly to forward() but has some restrictions. A Servlet can include() any number of resources that can each generate responses, but the resource is not allowed to set headers or commit a response.
  • 11. Request Dispatcher Ex if(name.equals(&quot;&quot;) || age.equals(&quot;&quot;)){ RequestDispatcher rd=request.getRequestDispatcher(&quot;AnotherServlet&quot;); rd.forward(request,response); return; } Here if name and age are equal to null then control will get passed to another servlet which perform further processing.
  • 12. ServletContext The javax.servlet.ServletContext interface represents a Servlet’s view of the Web Application it belongs to. Through the ServletContext interface, a Servlet can access raw input streams to Web Application resources, virtual directory translation, a common mechanism for logging information, and an application scope for binding objects. Individual container vendors provide specific implementations of ServletContext objects, but they all provide the same functionality defined by the ServletContext interface. A ServletContext object implements similar getInitParam() and getInitParamNames() methods demonstrated for ServletConfig. The difference is that these methods do not access initial parameters for a particular Servlet, but rather parameters specified for the entire Web Application. <web-app> <context-param> <param-name>admin email</param-name> <param-value>[email protected]</param-value> </context-param> <servlet> <servlet-name>helloworld</servlet-name> <servlet-class>com.jspbook.HelloWorld</servlet-class>
  • 13. response.setContentType(&quot;text/html&quot;); PrintWriter out = response.getWriter(); out.println(&quot;<html>&quot;); out.println(&quot;<head>&quot;); out.println(&quot;<title>An Error Has Occurred!</title>&quot;); out.println(&quot;</head>&quot;); out.println(&quot;<body>&quot;); ServletContext sc = getServletConfig().getServletContext(); String adminEmail = sc.getInitParameter(&quot;admin email&quot;); out.println(&quot;<h1>Error Page</h1>&quot;); out.print(&quot;Sorry! An unexpected error has occurred.&quot;); out.print(&quot;Please send an error report to &quot;+adminEmail+&quot;.&quot;); out.println(&quot;</body>&quot;); out.println(&quot;</html>&quot;); } }