SlideShare a Scribd company logo
WEB TECHNOLOGIES Servlet
Dr R Jegadeesan Prof-CSE
Jyothishmathi Institute of Technology and Science,
karimnagar
Syllabus
UNIT – III Servlet
Common Gateway Interface (CGI),
Lifecycle of a Servlet, deploying a
servlet, The Servlet API, Reading
Servlet parameters, Reading
Initialization parameters, Handling
Http Request & Responses, Using
Cookies and Sessions, connecting to
a database using JDBC.
2
UNIT - III : Servlet Programming
Aim & Objective :
➢ To introduce Server Side programming with Java Servlets.
➢ Servlet Technology is used to create web applications. Servlet
technology uses Java language to create web applications.
Introduction to Java Servlet
3
UNIT - III : Servlet Programming
Web applications are helper applications that resides at web server and build dynamic web pages.
A dynamic page could be anything like a page that randomly chooses picture to display or even a
page that displays the current time.
Introduction to Servlet
4
UNIT - III : Servlets
Before Servlets, CGI(Common Gateway Interface) programming was used to create web applications.
Here's how a CGI program works :User clicks a link that has URL to a dynamic page instead of a static
page. The URL decides which CGI program to execute.
Web Servers run the CGI program in separate OS shell. The shell includes OS environment and the
process to execute code of the CGI program. The CGI response is sent back to the Web Server, which
wraps the response in an HTTP response and send it back to the web browser
.
CGI (Common Gateway Interface)
5
UNIT - III : Servlet
•Less response time because each request runs in a separate thread.
•Servlets are scalable.
•Servlets are robust and object oriented.
•Servlets are platform independent.
Advantages of Servlet
6
UNIT - III : Servlet
Servlet API consists of two important packages that encapsulates all the important classes and
interface, namely :
javax.servlet
javax.servlet.http
Servlet API
7
INTERFACES CLASSES
Servlet ServletInputStream
ServletContext ServletOutputStream
ServletConfig ServletRequestWrapper
ServletRequest ServletResponseWrapper
ServletResponse ServletRequestEvent
ServletContextListener ServletContextEvent
RequestDispatcher ServletRequestAttributeEvent
SingleThreadModel ServletContextAttributeEvent
Filter ServletException
FilterConfig UnavailableException
FilterChain GenericServlet
ServletRequestListene
r
UNIT - III : Servlet
Servlet Interface provides five methods. Out of these five methods, three methods are Servlet life
cycle methods and rest two are non life cycle methods.
Servlet Interface
8
UNIT - III : Servlet
Web container is responsible for managing execution of servlets and JSP pages for Java EE application.
When a request comes in for a servlet, the server hands the request to the Web Container. Web Container is
responsible for instantiating the servlet or creating a new thread to handle the request. Its the job of Web
Container to get the request and response to the servlet. The container creates multiple threads to process
multiple requests to a single servlet.
Servlets don't have a main() method. Web Container manages the life cycle of a Servlet instance.
How a Servlet Application Works
9
UNIT - III : Servlet
Life Cycle of Servlet
10
Loading Servlet Class : A Servlet class is loaded when first request for the servlet is
received by the Web Container
.
Servlet instance creation :After the Servlet class is loaded, Web Container creates the
instance of it. Servlet instance is created only once in the life cycle.
Call to the init() method : init() method is called by the Web Container on servlet
instance to initialize the servlet.
UNIT - II : XML
Signature of init() method :
public void init(ServletConfig config) throws ServletException
Call to the service() method : The containers call the service() method each time the request for
servlet is received. The service() method will then call the doGet() or doPost() methos based ont
eh type of the HTTP request, as explained in previous lessons.
Signature of service() method :
public void service(ServletRequest request, ServletResponse response) throws ServletException,
IOException
Call to destroy() method: The Web Container call the destroy() method before removing servlet
instance, giving it a chance for cleanup activity.
Life cycle of Servlet
11
UNIT - III : Servlet
GenericServlet is an abstract class that provides implementation of most of the basic servlet
methods. This is a very important class.
Methods of GenericServlet class
public void init(ServletConfig)
public abstract void service(ServletRequest request,ServletResposne response)
public void destroy()
public ServletConfig getServletConfig()
public String getServletInfo()
public ServletContext getServletContext()
public String getInitParameter(String name)
public Enumeration getInitParameterNames()
public String getServletName()
public void log(String msg)
public void log(String msg, Throwable t)
GenericServlet Class
12
UNIT - III : Servlet
HttpServlet is also an abstract class. This class gives implementation of various service() methods
of Servlet interface.
To create a servlet, we should create a class that extends HttpServlet abstract class. The Servlet
class that we will create, must not override service() method. Our servlet class will override only the
doGet() and/or doPost() methods.
The service() method of HttpServlet class listens to the Http methods (GET
, POST etc) from request
stream and invokes doGet() or doPost() methods based on Http Method type.
HTTP Servlet Class
13
UNIT - III : Servlet
Web container is responsible for managing execution of servlets and JSP pages for Java EE
application.
When a request comes in for a servlet, the server hands the request to the Web Container
. Web
Container is responsible for instantiating the servlet or creating a new thread to handle the request.
Its the job of Web Container to get the request and response to the servlet. The container creates
multiple threads to process multiple requests to a single servlet.
Servlets don't have a main() method. Web Container manages the life cycle of a Servlet instance.
How a Servlet Application Works
14
UNIT - III : Servlet
Servlets can be used for handling both the GET Requests and the POST Requests. The HttpServlet
class is used for handling HTTP GET Requests as it has some specialized methods that can
efficiently handle the HTTP requests.
These methods are:
doGet() ,
doPost(),
doPut(),
doDelete, etc
Handling HTTP request & Responses
15
UNIT - III : Servlet
<html><body>
<form action="numServlet">
select the Number:
<select name="number" size="3">
<option value="one">One</option>
<option value="Two">Two</option>
<option value="Three">Three</option>
</select>
<input type="submit">
</body></html>
Handling HTTP request & Responses
16
UNIT - III : Servlet
Handling HTTP request & Responses
17
The ServletRequest class includes methods that allow you to read the names and values of
parameters that are included in a client request. We will develop a servlet that illustrates their
use. The example contains two files.
A Web page is defined in sum.html and a servlet is defined in Add.java
<html><body><center>
<form name="Form1" method="post" action="Add">
<table><tr><td><B>Enter First Number</td>
<td><input type=textbox name="Enter First Number" size="25" value=""></td>
</tr>
<tr><td><B>Enter Second Number</td>
<td><input type=textbox name="Enter Second Number" size="25" value=""></td>
</tr></table>
<input type=submit value="Submit“></body></html>
UNIT - III : Servlet
Reading Servlet Parameters
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Add
extends HttpServlet
{
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Get print writer
.
response.getContentType("text/html");
PrintWriter pw = response.getWriter();
// Get enumeration of parameter names.
Enumeration e = request.getParameterNames();
// Display parameter names and values.
int sum=0;
UNIT - III : Servlet
Handling HTTP request & Responses
while(e.hasMoreElements())
{
String pname = (String)e.nextElement();
pw.print(pname + " = ");
String pvalue = request.getParameter(pname);
sum+=Integer
.parseInt(pvalue);
pw.println(pvalue);
}
pw.println("Sum = "+sum);
pw.close(); } }
UNIT - III : Servlet
Handling HTTP request & Responses
• The source code for Add.java contains doPost( ) method is overridden to process client requests.
• The getParameterNames( ) method returns an enumeration of the parameter names. These are
processed in a loop.
• We can see that the parameter name and value are output to the client. The parameter value is
obtained via the getParameter( ) method.
URL : http://localhost:8080/servlets/sum.html
UNIT - III : Servlet
Handling HTTP request & Responses
UNIT III: Servlet
Reference
22
Book Details :
TEXT BOOKS:
1. Web Technologies, Uttam K Roy, Oxford University Press
2. The Complete Reference PHP – Steven Holzner, Tata McGraw-Hill
REFERENCE BOOKS:
1.Web Programming, building internet applications, Chris Bates 2nd edition, Wiley Dreamtech
2. Java Server Pages –Hans Bergsten, SPD O’Reilly
3. Java Script, D. Flanagan, O’Reilly,SPD.
4. Beginning Web Programming-Jon Duckett WROX.
5. Programming World Wide Web, R. W
. Sebesta, Fourth Edition, Pearson.
6. Internet and World Wide Web – How to program, Dietel and Nieto, Pearson.
UNIT III : Servlet
Video Reference
23
Video Link details (NPTEL, YOUTUBE Lectures and etc.)
➢https://nptel.ac.in/content/storage2/nptel_ data3/html/mhrd/ict/text/106106093/lec39.pdf
➢http://www.nptelvideos.in/2012/11/internet-technologies.html
➢https://nptel.ac.in/courses/106105191/
UNIT III : Servlet
Courses
24
courses available on <www.coursera.org>, and http://neat.aicte-india.org
https://www.coursera.org/
Course 1 : Web Applications for Everybody Specialization
Build dynamic database-backed web sites.. Use PHP
, MySQL, jQuery, and Handlebars to build web
and database applications.
Course 2: Java Programming: Solving Problems with Software
Learn to Design and Create Websites. Build a responsive and accessible web portfolio using
HTML5, Java Servlet, XML, CSS3, and JavaScript
UNIT-III : Servlet Programming
Tutorial Topic
25
Tutorial topic wise
➢www.geeksforgeeks.org › introduction-java-servlets
➢www.edureka.co › blog › java-servlets
➢beginnersbook.com › servlet-tutorial
➢www.tutorialspoint.com › servlets
➢www.javatpoint.com › servlet-tutorial
UNIT-III : Servlet
Multiple Choice Questions
26
Servlet – MCQs
1. Which of the following code is used to get an attribute in a HTTP Session object in servlets?
A. session.getAttribute(String name) B. session.alterAttribute(String name)
C. session.updateAttribute(String name) D. session.setAttribute(String name)
2. Which method is used to specify before any lines that uses the PintWriter?
A. setPageType() B. setContextType()
C. setContentType() D. setResponseType()
3. What are the functions of Servlet container?
A. Lifecycle management B. Communication support
C. Multithreading support D. All of the above
4. What is bytecode?
A. Machine-specific code B. Java code
C. Machine-independent code D. None of the mentioned
5. Which object of HttpSession can be used to view and manipulate information about a
session?
A. session identifier B. creation time
C. last accessed time D. All mentioned above
UNIT-III : Servlet
Servlet-Tutorial Problems
27
Servlet –Tutorial Problems:
1.Write a Servlet program to read employee details
2.Write a Servlet program to uploads files to remote directory
UNIT-III : Servlet
Question Bank
28
PHP –universities & Important Questions:
1. Define a session tracker that tracks the number of accesses and last access data of a
particular web page.
2. What is the security issues related to Servlets.
3. Explain how HTTP POST request is processed using Servlets
4. Explain how cookies are used for session tracking?
5. Explain about Tomcat web server
.
6. What is Servlet? Explain life cycle of a Servlet?
7. What are the advantages of Servlets over CGI
8. What is session tracking? Explain different mechanisms of session tracking?
9. What is the difference between Servlets and applets?
10. What is the difference between doGet() and doPost()?
Thank you
29

More Related Content

What's hot (20)

PPT
Java Servlets
BG Java EE Course
 
PPS
Jdbc architecture and driver types ppt
kamal kotecha
 
PPTX
Classes, objects in JAVA
Abhilash Nair
 
PPTX
Java Server Pages
Kasun Madusanke
 
PPS
Java rmi
kamal kotecha
 
PPTX
Introduction to Angularjs
Manish Shekhawat
 
PPSX
JDBC: java DataBase connectivity
Tanmoy Barman
 
PPTX
Database Connectivity in PHP
Taha Malampatti
 
PPT
Web Servers (ppt)
webhostingguy
 
PPTX
Introduction to EJB
Return on Intelligence
 
PPTX
Threads in JAVA
Haldia Institute of Technology
 
PPTX
Form Handling using PHP
Nisa Soomro
 
PPTX
Client server architecture
Bhargav Amin
 
PPTX
Java servlets and CGI
lavanya marichamy
 
PDF
WEB I - 01 - Introduction to Web Development
Randy Connolly
 
PPTX
Servlets
ZainabNoorGul
 
PPT
Java tutorial PPT
Intelligo Technologies
 
PPTX
Validation Controls in asp.net
Deep Patel
 
PPTX
JDBC ppt
Rohit Jain
 
PPT
Introduction to .NET Framework
Raghuveer Guthikonda
 
Java Servlets
BG Java EE Course
 
Jdbc architecture and driver types ppt
kamal kotecha
 
Classes, objects in JAVA
Abhilash Nair
 
Java Server Pages
Kasun Madusanke
 
Java rmi
kamal kotecha
 
Introduction to Angularjs
Manish Shekhawat
 
JDBC: java DataBase connectivity
Tanmoy Barman
 
Database Connectivity in PHP
Taha Malampatti
 
Web Servers (ppt)
webhostingguy
 
Introduction to EJB
Return on Intelligence
 
Form Handling using PHP
Nisa Soomro
 
Client server architecture
Bhargav Amin
 
Java servlets and CGI
lavanya marichamy
 
WEB I - 01 - Introduction to Web Development
Randy Connolly
 
Servlets
ZainabNoorGul
 
Java tutorial PPT
Intelligo Technologies
 
Validation Controls in asp.net
Deep Patel
 
JDBC ppt
Rohit Jain
 
Introduction to .NET Framework
Raghuveer Guthikonda
 

Similar to WEB TECHNOLOGIES Servlet (20)

PPTX
Enterprise java unit-1_chapter-3
sandeep54552
 
PPTX
21CS642 Module 4_1 Servlets PPT.pptx VI SEM CSE Students
VENKATESHBHAT25
 
PPTX
SERVLET in web technolgy engineering.pptx
ARUNKUMARM230658
 
PPT
Servlet ppt by vikas jagtap
Vikas Jagtap
 
PPTX
UNIT-3 Servlet
ssbd6985
 
PPT
Servlets
Sasidhar Kothuru
 
PPTX
java Servlet technology
Tanmoy Barman
 
PPTX
JAVA SERVLETS acts as a middle layer between a request coming from a web brow...
ssuser4f7d71
 
PPTX
18CSC311J Web Design and Development UNIT-3
Sivakumar M
 
PPTX
Servlets
Akshay Ballarpure
 
PPT
JAVA Servlets
deepak kumar
 
PPT
Anintroductiontojavawebtechnology 090324184240-phpapp01
raviIITRoorkee
 
PPT
Module 4.pptModule 4.pptModule 4.pptModule 4.ppt
tahirnaquash2
 
PPTX
Java Servlet
Yoga Raja
 
PPTX
Wt unit 3
team11vgnt
 
PPTX
Servlets-UNIT3and introduction to servlet
RadhikaP41
 
PPT
Web Tech Java Servlet Update1
vikram singh
 
PPT
An Introduction To Java Web Technology
vikram singh
 
PDF
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Tushar B Kute
 
PPTX
Chapter 3 servlet & jsp
Jafar Nesargi
 
Enterprise java unit-1_chapter-3
sandeep54552
 
21CS642 Module 4_1 Servlets PPT.pptx VI SEM CSE Students
VENKATESHBHAT25
 
SERVLET in web technolgy engineering.pptx
ARUNKUMARM230658
 
Servlet ppt by vikas jagtap
Vikas Jagtap
 
UNIT-3 Servlet
ssbd6985
 
java Servlet technology
Tanmoy Barman
 
JAVA SERVLETS acts as a middle layer between a request coming from a web brow...
ssuser4f7d71
 
18CSC311J Web Design and Development UNIT-3
Sivakumar M
 
JAVA Servlets
deepak kumar
 
Anintroductiontojavawebtechnology 090324184240-phpapp01
raviIITRoorkee
 
Module 4.pptModule 4.pptModule 4.pptModule 4.ppt
tahirnaquash2
 
Java Servlet
Yoga Raja
 
Wt unit 3
team11vgnt
 
Servlets-UNIT3and introduction to servlet
RadhikaP41
 
Web Tech Java Servlet Update1
vikram singh
 
An Introduction To Java Web Technology
vikram singh
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Tushar B Kute
 
Chapter 3 servlet & jsp
Jafar Nesargi
 
Ad

More from Jyothishmathi Institute of Technology and Science Karimnagar (20)

PDF
JAVA PROGRAMMING- GUI Programming with Swing - The Swing Buttons
Jyothishmathi Institute of Technology and Science Karimnagar
 
PDF
JAVA PROGRAMMING - The Collections Framework
Jyothishmathi Institute of Technology and Science Karimnagar
 
PDF
JAVA PROGRAMMING- Exception handling - Multithreading
Jyothishmathi Institute of Technology and Science Karimnagar
 
PDF
JAVA PROGRAMMING – Packages - Stream based I/O
Jyothishmathi Institute of Technology and Science Karimnagar
 
PDF
Java programming -Object-Oriented Thinking- Inheritance
Jyothishmathi Institute of Technology and Science Karimnagar
 
PDF
Compiler Design- Machine Independent Optimizations
Jyothishmathi Institute of Technology and Science Karimnagar
 
PDF
COMPILER DESIGN Run-Time Environments
Jyothishmathi Institute of Technology and Science Karimnagar
 
PDF
COMPILER DESIGN- Syntax Directed Translation
Jyothishmathi Institute of Technology and Science Karimnagar
 
PDF
COMPILER DESIGN- Introduction & Lexical Analysis:
Jyothishmathi Institute of Technology and Science Karimnagar
 
PPTX
CRYPTOGRAPHY AND NETWORK SECURITY- E-Mail Security
Jyothishmathi Institute of Technology and Science Karimnagar
 
PDF
CRYPTOGRAPHY AND NETWORK SECURITY- Transport-level Security
Jyothishmathi Institute of Technology and Science Karimnagar
 
PDF
CRYPTOGRAPHY & NETWORK SECURITY- Cryptographic Hash Functions
Jyothishmathi Institute of Technology and Science Karimnagar
 
PDF
CRYPTOGRAPHY & NETWOK SECURITY- Symmetric key Ciphers
Jyothishmathi Institute of Technology and Science Karimnagar
 
PDF
Computer Forensics Working with Windows and DOS Systems
Jyothishmathi Institute of Technology and Science Karimnagar
 
JAVA PROGRAMMING- GUI Programming with Swing - The Swing Buttons
Jyothishmathi Institute of Technology and Science Karimnagar
 
JAVA PROGRAMMING - The Collections Framework
Jyothishmathi Institute of Technology and Science Karimnagar
 
JAVA PROGRAMMING- Exception handling - Multithreading
Jyothishmathi Institute of Technology and Science Karimnagar
 
JAVA PROGRAMMING – Packages - Stream based I/O
Jyothishmathi Institute of Technology and Science Karimnagar
 
Java programming -Object-Oriented Thinking- Inheritance
Jyothishmathi Institute of Technology and Science Karimnagar
 
Compiler Design- Machine Independent Optimizations
Jyothishmathi Institute of Technology and Science Karimnagar
 
COMPILER DESIGN- Syntax Directed Translation
Jyothishmathi Institute of Technology and Science Karimnagar
 
COMPILER DESIGN- Introduction & Lexical Analysis:
Jyothishmathi Institute of Technology and Science Karimnagar
 
CRYPTOGRAPHY AND NETWORK SECURITY- E-Mail Security
Jyothishmathi Institute of Technology and Science Karimnagar
 
CRYPTOGRAPHY AND NETWORK SECURITY- Transport-level Security
Jyothishmathi Institute of Technology and Science Karimnagar
 
CRYPTOGRAPHY & NETWORK SECURITY- Cryptographic Hash Functions
Jyothishmathi Institute of Technology and Science Karimnagar
 
CRYPTOGRAPHY & NETWOK SECURITY- Symmetric key Ciphers
Jyothishmathi Institute of Technology and Science Karimnagar
 
Computer Forensics Working with Windows and DOS Systems
Jyothishmathi Institute of Technology and Science Karimnagar
 
Ad

Recently uploaded (20)

PPTX
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
PDF
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
PDF
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
PDF
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 

WEB TECHNOLOGIES Servlet

  • 1. WEB TECHNOLOGIES Servlet Dr R Jegadeesan Prof-CSE Jyothishmathi Institute of Technology and Science, karimnagar
  • 2. Syllabus UNIT – III Servlet Common Gateway Interface (CGI), Lifecycle of a Servlet, deploying a servlet, The Servlet API, Reading Servlet parameters, Reading Initialization parameters, Handling Http Request & Responses, Using Cookies and Sessions, connecting to a database using JDBC. 2
  • 3. UNIT - III : Servlet Programming Aim & Objective : ➢ To introduce Server Side programming with Java Servlets. ➢ Servlet Technology is used to create web applications. Servlet technology uses Java language to create web applications. Introduction to Java Servlet 3
  • 4. UNIT - III : Servlet Programming Web applications are helper applications that resides at web server and build dynamic web pages. A dynamic page could be anything like a page that randomly chooses picture to display or even a page that displays the current time. Introduction to Servlet 4
  • 5. UNIT - III : Servlets Before Servlets, CGI(Common Gateway Interface) programming was used to create web applications. Here's how a CGI program works :User clicks a link that has URL to a dynamic page instead of a static page. The URL decides which CGI program to execute. Web Servers run the CGI program in separate OS shell. The shell includes OS environment and the process to execute code of the CGI program. The CGI response is sent back to the Web Server, which wraps the response in an HTTP response and send it back to the web browser . CGI (Common Gateway Interface) 5
  • 6. UNIT - III : Servlet •Less response time because each request runs in a separate thread. •Servlets are scalable. •Servlets are robust and object oriented. •Servlets are platform independent. Advantages of Servlet 6
  • 7. UNIT - III : Servlet Servlet API consists of two important packages that encapsulates all the important classes and interface, namely : javax.servlet javax.servlet.http Servlet API 7 INTERFACES CLASSES Servlet ServletInputStream ServletContext ServletOutputStream ServletConfig ServletRequestWrapper ServletRequest ServletResponseWrapper ServletResponse ServletRequestEvent ServletContextListener ServletContextEvent RequestDispatcher ServletRequestAttributeEvent SingleThreadModel ServletContextAttributeEvent Filter ServletException FilterConfig UnavailableException FilterChain GenericServlet ServletRequestListene r
  • 8. UNIT - III : Servlet Servlet Interface provides five methods. Out of these five methods, three methods are Servlet life cycle methods and rest two are non life cycle methods. Servlet Interface 8
  • 9. UNIT - III : Servlet Web container is responsible for managing execution of servlets and JSP pages for Java EE application. When a request comes in for a servlet, the server hands the request to the Web Container. Web Container is responsible for instantiating the servlet or creating a new thread to handle the request. Its the job of Web Container to get the request and response to the servlet. The container creates multiple threads to process multiple requests to a single servlet. Servlets don't have a main() method. Web Container manages the life cycle of a Servlet instance. How a Servlet Application Works 9
  • 10. UNIT - III : Servlet Life Cycle of Servlet 10 Loading Servlet Class : A Servlet class is loaded when first request for the servlet is received by the Web Container . Servlet instance creation :After the Servlet class is loaded, Web Container creates the instance of it. Servlet instance is created only once in the life cycle. Call to the init() method : init() method is called by the Web Container on servlet instance to initialize the servlet.
  • 11. UNIT - II : XML Signature of init() method : public void init(ServletConfig config) throws ServletException Call to the service() method : The containers call the service() method each time the request for servlet is received. The service() method will then call the doGet() or doPost() methos based ont eh type of the HTTP request, as explained in previous lessons. Signature of service() method : public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException Call to destroy() method: The Web Container call the destroy() method before removing servlet instance, giving it a chance for cleanup activity. Life cycle of Servlet 11
  • 12. UNIT - III : Servlet GenericServlet is an abstract class that provides implementation of most of the basic servlet methods. This is a very important class. Methods of GenericServlet class public void init(ServletConfig) public abstract void service(ServletRequest request,ServletResposne response) public void destroy() public ServletConfig getServletConfig() public String getServletInfo() public ServletContext getServletContext() public String getInitParameter(String name) public Enumeration getInitParameterNames() public String getServletName() public void log(String msg) public void log(String msg, Throwable t) GenericServlet Class 12
  • 13. UNIT - III : Servlet HttpServlet is also an abstract class. This class gives implementation of various service() methods of Servlet interface. To create a servlet, we should create a class that extends HttpServlet abstract class. The Servlet class that we will create, must not override service() method. Our servlet class will override only the doGet() and/or doPost() methods. The service() method of HttpServlet class listens to the Http methods (GET , POST etc) from request stream and invokes doGet() or doPost() methods based on Http Method type. HTTP Servlet Class 13
  • 14. UNIT - III : Servlet Web container is responsible for managing execution of servlets and JSP pages for Java EE application. When a request comes in for a servlet, the server hands the request to the Web Container . Web Container is responsible for instantiating the servlet or creating a new thread to handle the request. Its the job of Web Container to get the request and response to the servlet. The container creates multiple threads to process multiple requests to a single servlet. Servlets don't have a main() method. Web Container manages the life cycle of a Servlet instance. How a Servlet Application Works 14
  • 15. UNIT - III : Servlet Servlets can be used for handling both the GET Requests and the POST Requests. The HttpServlet class is used for handling HTTP GET Requests as it has some specialized methods that can efficiently handle the HTTP requests. These methods are: doGet() , doPost(), doPut(), doDelete, etc Handling HTTP request & Responses 15
  • 16. UNIT - III : Servlet <html><body> <form action="numServlet"> select the Number: <select name="number" size="3"> <option value="one">One</option> <option value="Two">Two</option> <option value="Three">Three</option> </select> <input type="submit"> </body></html> Handling HTTP request & Responses 16
  • 17. UNIT - III : Servlet Handling HTTP request & Responses 17
  • 18. The ServletRequest class includes methods that allow you to read the names and values of parameters that are included in a client request. We will develop a servlet that illustrates their use. The example contains two files. A Web page is defined in sum.html and a servlet is defined in Add.java <html><body><center> <form name="Form1" method="post" action="Add"> <table><tr><td><B>Enter First Number</td> <td><input type=textbox name="Enter First Number" size="25" value=""></td> </tr> <tr><td><B>Enter Second Number</td> <td><input type=textbox name="Enter Second Number" size="25" value=""></td> </tr></table> <input type=submit value="Submit“></body></html> UNIT - III : Servlet Reading Servlet Parameters
  • 19. import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class Add extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get print writer . response.getContentType("text/html"); PrintWriter pw = response.getWriter(); // Get enumeration of parameter names. Enumeration e = request.getParameterNames(); // Display parameter names and values. int sum=0; UNIT - III : Servlet Handling HTTP request & Responses
  • 20. while(e.hasMoreElements()) { String pname = (String)e.nextElement(); pw.print(pname + " = "); String pvalue = request.getParameter(pname); sum+=Integer .parseInt(pvalue); pw.println(pvalue); } pw.println("Sum = "+sum); pw.close(); } } UNIT - III : Servlet Handling HTTP request & Responses
  • 21. • The source code for Add.java contains doPost( ) method is overridden to process client requests. • The getParameterNames( ) method returns an enumeration of the parameter names. These are processed in a loop. • We can see that the parameter name and value are output to the client. The parameter value is obtained via the getParameter( ) method. URL : http://localhost:8080/servlets/sum.html UNIT - III : Servlet Handling HTTP request & Responses
  • 22. UNIT III: Servlet Reference 22 Book Details : TEXT BOOKS: 1. Web Technologies, Uttam K Roy, Oxford University Press 2. The Complete Reference PHP – Steven Holzner, Tata McGraw-Hill REFERENCE BOOKS: 1.Web Programming, building internet applications, Chris Bates 2nd edition, Wiley Dreamtech 2. Java Server Pages –Hans Bergsten, SPD O’Reilly 3. Java Script, D. Flanagan, O’Reilly,SPD. 4. Beginning Web Programming-Jon Duckett WROX. 5. Programming World Wide Web, R. W . Sebesta, Fourth Edition, Pearson. 6. Internet and World Wide Web – How to program, Dietel and Nieto, Pearson.
  • 23. UNIT III : Servlet Video Reference 23 Video Link details (NPTEL, YOUTUBE Lectures and etc.) ➢https://nptel.ac.in/content/storage2/nptel_ data3/html/mhrd/ict/text/106106093/lec39.pdf ➢http://www.nptelvideos.in/2012/11/internet-technologies.html ➢https://nptel.ac.in/courses/106105191/
  • 24. UNIT III : Servlet Courses 24 courses available on <www.coursera.org>, and http://neat.aicte-india.org https://www.coursera.org/ Course 1 : Web Applications for Everybody Specialization Build dynamic database-backed web sites.. Use PHP , MySQL, jQuery, and Handlebars to build web and database applications. Course 2: Java Programming: Solving Problems with Software Learn to Design and Create Websites. Build a responsive and accessible web portfolio using HTML5, Java Servlet, XML, CSS3, and JavaScript
  • 25. UNIT-III : Servlet Programming Tutorial Topic 25 Tutorial topic wise ➢www.geeksforgeeks.org › introduction-java-servlets ➢www.edureka.co › blog › java-servlets ➢beginnersbook.com › servlet-tutorial ➢www.tutorialspoint.com › servlets ➢www.javatpoint.com › servlet-tutorial
  • 26. UNIT-III : Servlet Multiple Choice Questions 26 Servlet – MCQs 1. Which of the following code is used to get an attribute in a HTTP Session object in servlets? A. session.getAttribute(String name) B. session.alterAttribute(String name) C. session.updateAttribute(String name) D. session.setAttribute(String name) 2. Which method is used to specify before any lines that uses the PintWriter? A. setPageType() B. setContextType() C. setContentType() D. setResponseType() 3. What are the functions of Servlet container? A. Lifecycle management B. Communication support C. Multithreading support D. All of the above 4. What is bytecode? A. Machine-specific code B. Java code C. Machine-independent code D. None of the mentioned 5. Which object of HttpSession can be used to view and manipulate information about a session? A. session identifier B. creation time C. last accessed time D. All mentioned above
  • 27. UNIT-III : Servlet Servlet-Tutorial Problems 27 Servlet –Tutorial Problems: 1.Write a Servlet program to read employee details 2.Write a Servlet program to uploads files to remote directory
  • 28. UNIT-III : Servlet Question Bank 28 PHP –universities & Important Questions: 1. Define a session tracker that tracks the number of accesses and last access data of a particular web page. 2. What is the security issues related to Servlets. 3. Explain how HTTP POST request is processed using Servlets 4. Explain how cookies are used for session tracking? 5. Explain about Tomcat web server . 6. What is Servlet? Explain life cycle of a Servlet? 7. What are the advantages of Servlets over CGI 8. What is session tracking? Explain different mechanisms of session tracking? 9. What is the difference between Servlets and applets? 10. What is the difference between doGet() and doPost()?