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

WEB TECHNOLOGIES Servlet

  • 1.
    WEB TECHNOLOGIES Servlet DrR Jegadeesan Prof-CSE Jyothishmathi Institute of Technology and Science, karimnagar
  • 2.
    Syllabus UNIT – IIIServlet 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 classincludes 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.*; importjavax.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 sourcecode 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 BookDetails : 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 : ServletProgramming 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 MultipleChoice 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-TutorialProblems 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 QuestionBank 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()?
  • 29.