SlideShare a Scribd company logo
Wt unit 3
UNIT-3
Introduction to Servlets
Concepts of CGI
What is CGI ?
The Common Gateway Interface, or CGI, is a set of standards
that define how information is exchanged between the web
server and a custom script.
The Common Gateway Interface, or CGI, is a standard for
external gateway programs to interface with information
servers such as HTTP servers.
Concepts of CGI
CGI technology enables the web server to call an external
program and pass HTTP request information to the external
program to process the request.
For each request, it starts a new process.
Concepts of CGI
CGI Architecture Diagram
Disadvantages of CGI
There are many problems in CGI technology:
1. If number of clients increases, it takes more time for sending
response.
2. For each request, it starts a process and Web server is limited
to start processes.
3. It uses platform dependent language e.g. C, C++, perl.
Concepts of Servlets
What is a Servlet?
Servlet can be described in many ways, depending on the context.
•Servlet is a technology i.e. used to create web application.
•Servlet is an API that provides many interfaces and classes
including documentations.
•Servlet is an interface that must be implemented for creating any
servlet.
•Servlet is a class that extend the capabilities of the servers and
respond to the incoming request. It can respond to any type of
requests.
•Servlet is a web component that is deployed on the server to
create dynamic web page.
Concepts of Servlets
Concepts of Servlets
Advantage of Servlet
There are many advantages of servlet over CGI.
The basic benefits of servlet are as follows:
•better performance: because it creates a thread for each request
not process.
•Portability: because it uses java language.
•Robust: Servlets are managed by JVM so we don't need to worry
about memory leak, garbage collection etc.
•Secure: because it uses java language..
Concepts of Servlets
Advantage of Servlet
The web container creates threads for handling the multiple requests to the
servlet.
Threads have a lot of benefits over the Processes such as they share a common
memory area, lightweight, cost of communication between the threads are low.
Concepts of Servlets
Life Cycle of a Servlet (Servlet Life Cycle)
The web container maintains the life cycle of a servlet instance.
Let's see the life cycle of the servlet:
Servlet class is loaded.
Servlet instance is created.
init method is invoked.
service method is invoked.
destroy method is invoked.
Concepts of Servlets
Life Cycle of a Servlet (Servlet Life Cycle)
Concepts of Servlets
Servlet Life Cycle methods
The init() Method:
The init method is called only once.
It is called only when the servlet is created, and not
called for any user requests afterwards.
The init method definition looks like this −
public void init() throws ServletException
{
// Initialization code...
}
Concepts of Servlets
Servlet Life Cycle methods(cont..)
The service() Method
The service() method is the main method to perform the
actual task.
The servlet container (i.e. web server) calls the service()
method to handle requests coming from the client(
browsers) and to write the formatted response back to
the client.
The service() method checks the HTTP request type
(GET, POST, PUT, DELETE, etc.) and calls doGet, doPost,
doPut, doDelete, etc. methods as appropriate.
Concepts of Servlets
Servlet Life Cycle methods(cont..)
The service() Method
Here is the signature of this method −
public void service(ServletRequest request, ServletResponse response) throws
ServletException, IOException
{
…..
…
}
We have nothing to do with service() method but you override
either doGet() or doPost() depending on what type of request
you receive from the client.
Concepts of Servlets
Servlet Life Cycle methods(cont..)
The destroy() Method
The destroy() method is called only once at the end of
the life cycle of a servlet.
This method gives your servlet a chance to close
database connections, halt background threads, write
cookie lists or hit counts to disk, and perform other such
cleanup activities.
public void destroy()
{ // Finalization code...
}
Concepts of Servlets
Servlet Life Cycle Scenario
Sample Code of Servlets
//Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class HelloWorld extends HttpServlet {
private String message;
public void init() throws ServletException {
// Do required initialization
message = "Hello World";
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");
// Actual logic goes here.
PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}
public void destroy() {
// do nothing.
}
}
Compiling Servlets
Compiling a Servlet:
1. Let us create a file with name HelloWorld.java with the code
shown above.
2. Place this file at C:ServletDevel (in Windows) or at
/usr/ServletDevel (in Unix).
3. This path location must be added to CLASSPATH before
proceeding further.
4. Assuming your environment is setup properly, go
in ServletDevel directory and compile HelloWorld.java as follows
−
$ javac HelloWorld.java
Compiling Servlets(con..)
5. If the servlet depends on any other libraries, you have to
include those JAR files on your CLASSPATH as well.
6. Include only servlet-api.jar JAR file because if you are not
using any other library in Hello World program.
7. If everything goes fine, above compilation would
produce HelloWorld.class file in the same directory.
Next section would explain how a compiled servlet would be
deployed in production.
Servlets Deployment
Servlet Deployment:
Step 1: By default,
A servlet application is located at the path
<Tomcat-installationdirectory>/webapps/ROOT
and
the class file would reside in
<Tomcat-installationdirectory>/webapps/ROOT/WEB-
INF/classes.
If you have a fully qualified class name,
of com.myorg.MyServlet then this servlet class must be
located in WEB-INF/classes/com/myorg/MyServlet.class.
Servlets Deployment(con..)
Step 2:
let us copy HelloWorld.class into
<Tomcat-installationdirectory>/webapps/ROOT/WEB-
INF/classes
Step 3:
create following entries in web.xml file located in
<Tomcat-installation-directory>/webapps/ROOT/WEB-INF/
Servlets Deployment(cont..)
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
Above entries to be created inside <web-app>...</web-app> tags
available in web.xml file.
Servlets Deployment(cont..)
Step 4:
Start tomcat server using
<Tomcat-installationdirectory>binstartup.bat (on
Windows) or
<Tomcat-installationdirectory>/bin/startup.sh (on
Linux/Solaris etc.) and
Step 5:finally type
http://localhost:8080/HelloWorld
in the browser's address box.
Servlets Deployment(cont..)
Servlet API
The javax.servlet and javax.servlet.http packages
represent interfaces and classes for servlet api.
The javax.servlet package contains many
interfaces and classes that are used by the servlet or
web container. These are not specific to any
protocol.
The javax.servlet.http package contains interfaces
and classes that are responsible for http requests
only.
Servlets Deployment(cont..)
There are many interfaces in javax.servlet package. They are as
follows:
1. Servlet
2. ServletRequest
3. ServletResponse
4. RequestDispatcher
5. ServletConfig
6. ServletContext
7. SingleThreadModel
8. Filter
9. FilterConfig
10. FilterChain
11. ServletRequestListener
12. ServletRequestAttributeListener
13. ServletContextListener
14. ServletContextAttributeListener
Servlets Deployment(cont..)
There are many classes in javax.servlet package. They are as follows:
1. GenericServlet
2. ServletInputStream
3. ServletOutputStream
4. ServletRequestWrapper
5. ServletResponseWrapper
6. ServletRequestEvent
7. ServletContextEvent
8. ServletRequestAttributeEvent
9. ServletContextAttributeEvent
10. ServletException
11. UnavailableException
Servlets Deployment(cont..)
Interfaces in javax.servlet.http package
1. HttpServletRequest
2. HttpServletResponse
3. HttpSession
4. HttpSessionListener
5. HttpSessionAttributeListener
6. HttpSessionBindingListener
7. HttpSessionActivationListener
8. HttpSessionContext (deprecated now)
Servlets Deployment(cont..)
Classes in javax.servlet.http package
1. HttpServlet
2. Cookie
3. HttpServletRequestWrapper
4. HttpServletResponseWrapper
5. HttpSessionEvent
6. HttpSessionBindingEvent
7. HttpUtils (deprecated now)
Servlets Deployment(cont..)
Parameters in Servlets
The parameters are the way in which a client or user can
send information to the Http Server
Servlets Deployment(cont..)
Parameters in Servlets
For example,
in a login screen, we need to send to the server, the user
and the password so that it validates them.
Servlets Deployment(cont..)
Parameters in Servlets
For example,
How does the client or the Browser send these parameters
using the methods GET or POST,
The first thing we are going to do is to create in our site a page
"login.html" with the following content:
<html>
<body>
<form action="login" method="get">
<table>
<tr>
<td>User</td>
<td><input name="user" /></td>
</tr>
<tr>
<td>password</td>
<td><input name="password" /></td>
</tr>
</table>
<input type="submit" />
</form>
</body>
</html>
Servlets Deployment(cont..)
Parameters in Servlets
Then, we create a Servlet which receives the request
in /login , which is the indicated direction in
the action attribute of the tag <form> of login.html
Servlets Deployment(cont..)
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String user = req.getParameter("user");
String pass = req.getParameter("password");
if ("edu4java".equals(user) && "eli4java".equals(pass)) {
response(resp, "login ok");
} else {
response(resp, "invalid login");
}
}
Servlets Deployment(cont..)
private void response(HttpServletResponse resp, String msg)
throws IOException {
PrintWriter out = resp.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<t1>" + msg + "</t1>");
out.println("</body>");
out.println("</html>");
}
}
Servlets Deployment(cont..)
We modify web.xml to link /login with this Servlet.
<web-app>
<servlet>
<servlet-name>timeservlet</servlet-name>
<servlet-class>com.edu4java.servlets.FirstServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>login-servlet</servlet-name>
<servlet-class>com.edu4java.servlets.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>timeservlet</servlet-name>
<url-pattern>/what-time-is-it</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>login-servlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
Servlets Deployment(cont..)
Session Tracking and Cookies
Session Tracking:
Keeping track of a sequence of related requests sent
by a client to perform some designated task is known
as “Session Tracking”
Cookies are one of the solutions to session tracking.
Servlets Deployment(cont..)
Session Tracking and Cookies(cont..)
Cookies:
A cookie is a small piece of information that is persisted
between the multiple client requests.
A cookie has
 a name, a single value, and
 optional attributes such as a comment, path and
 domain qualifiers, a maximum age, and
 a version number.
Servlets Deployment(cont..)
Session Tracking and Cookies(cont..)
How Cookies Work:
Servlets Deployment(cont..)
Session Tracking and Cookies(cont..)
How Cookies Work:
•By default, each request is considered as a new request.
•we add cookie with response from the servlet.
•So cookie is stored in the cache of the browser.
•After that if request is sent by the user, cookie is added with
request by default.
•we recognize the user as the old user.
Servlets Deployment(cont..)
Session Tracking and Cookies(cont..)
How Cookies Work:
•By default, each request is considered as a new request.
•we add cookie with response from the servlet.
•So cookie is stored in the cache of the browser.
•After that if request is sent by the user, cookie is added with
request by default.
•we recognize the user as the old user.
Servlets Deployment(cont..)
Session Tracking and Cookies(cont..)
Types of Cookie
There are 2 types of cookies in servlets.
1. Non-persistent cookie
2. Persistent cookie
Non-persistent cookie
It is valid for single session only. It is removed each time
when user closes the browser.
Persistent cookie
It is valid for multiple session . It is not removed each
time when user closes the browser. It is removed only if
user logout or signout.
Servlets Deployment(cont..)
Session Tracking and Cookies(cont..)
Advantage of Cookies
Simplest technique of maintaining the state.
Cookies are maintained at client side.
Disadvantage of Cookies
It will not work if cookie is disabled from the browser.
Only textual information can be set in Cookie object.
Servlets Deployment(cont..)
Session Tracking and Cookies(cont..)
Cookie class
javax.servlet.http.Cookie class provides the functionality
of using cookies. It provides a lot of useful methods for
cookies.
Servlets Deployment(cont..)
Session Tracking and Cookies(cont..)
Constructor of Cookie class
Cookie() : constructs a cookie.
Cookie(String name, String value) : constructs a cookie
with a specified name and value.
Servlets Deployment(cont..)
Session Tracking and Cookies(cont..)
Method Descriptionpublic
Public void setMaxAge(int expiry) Sets the maximum age
of the cookie in seconds.
public String getName() Returns the name of the cookie.
The name cannot be changed after creation.
public String getValue() Returns the value of the cookie.
public void setName(String name) changes the name
of the cookie.
public void setValue(String value) changes the value
of the cookie
Servlets Deployment(cont..)
Session Tracking and Cookies(cont..)
How to send Cookies to the Client( 3 steps )
1) Create a Cookie object.
Cookie c = new Cookie("userName",”Vits");
2) Set the maximum Age:
c.setMaxAge(1800); // value in seconds
3) Place the Cookie in HTTP response header:
response.addCookie(c);
Servlets Deployment(cont..)
Session Tracking and Cookies(cont..)
How to Read Cookies from the Client/browser
Cookie c[]=request.getCookies(); //c.length gives the cookie
count
for(int i=0;i<c.length;i++)
{
out.print("Name: "+c[i].getName()+" & Value:
"+c[i].getValue());
}
Servlets Deployment(cont..)
Session Tracking and Cookies(cont..)
How to delete Cookies from the Client/browser
If you want to delete a cookie then you simply need to follow up following
three steps −
Read an already existing cookie and store it in Cookie object.
Set cookie age as zero using setMaxAge() method to delete an existing
cookie
Add this cookie back into response header.
Servlets Deployment(cont..)
Session Tracking and Cookies(cont..)
How to delete Cookies from the Client/browser
Let's see the simple code to delete cookie.
It is mainly used to logout or sign out the user.
Cookie ck=new Cookie("user",""); //deleting value of cookie
ck.setMaxAge(0); //changing the maximum age to 0 seconds
response.addCookie(ck); //adding cookie in the response
Servlets Deployment(cont..)
Session Tracking and Cookies(cont..)
Http Sessions
A session contains information specific to a particular user
across the whole application.
In such case, container creates a session id for each user.
The container uses this id to identify the particular user.
This unique ID can be stored into a cookie or in a request
parameter.
The HttpSession stays alive until it has not been used for
more than the timeout value specified in tag in deployment
descriptor file.
The default timeout value is 30 minutes, this is used if you
don’t specify the value in tag.
Servlets Deployment(cont..)
Session Tracking and Cookies(cont..)
Http Sessions(cont..)
Servlets Deployment(cont..)
Session Tracking and Cookies(cont..)
Http Sessions(cont..)
This is how you create a HttpSession object.
protected void doPost(HttpServletRequest req,
HttpServletResponse res) throws ServletException,
IOException
{
HttpSession session = req.getSession();
}
Servlets Deployment(cont..)
Http Sessions(cont..)
How you can store user information in
HttpSession object.
setAttribute(): method stores user information session
object
later when needed this information can be fetched from
the session.
Servlets Deployment(cont..)
Http Sessions(cont..)
How you can store user information in
HttpSession object.
Example: storing username, email-id and user age in
session with the attribute name uName, uemailId and
uAge respectively.
session.setAttribute("uName", "Chaitanya");
session.setAttribute("uemailId", "myemailid@gmail.com");
session.setAttribute("uAge", "30");
Servlets Deployment(cont..)
Http Sessions(cont..)
TO get the value from session we use the
getAttribute() method of HttpSession interface.
Example:
String userName = (String) session.getAttribute("uName");
String userEmailId = (String) session.getAttribute("uemailId");
String userAge = (String) session.getAttribute("uAge");
Servlets Deployment(cont..)
Http Sessions(cont..)
Sr.No. Method & Description
1
public Object getAttribute(String name)
This method returns the object bound with the specified
name in this session, or null if no object is bound under
the name.
2
public Enumeration getAttributeNames()
This method returns an Enumeration of String objects
containing the names of all the objects bound to this
session.
3
public long getCreationTime()
This method returns the time when this session was
created, measured in milliseconds since midnight January
1, 1970 GMT.
4
public String getId()
This method returns a string containing the unique
identifier assigned to this session.
Servlets Deployment(cont..)
Http Sessions(cont..)
Sr.No. Method & Description
5
public long getLastAccessedTime()
This method returns the last accessed time of the session,
in the format of milliseconds since midnight January 1,
1970 GMT
6
public int getMaxInactiveInterval()
This method returns the maximum time interval
(seconds), that the servlet container will keep the session
open between client accesses.
7
public void invalidate()
This method invalidates this session and unbinds any
objects bound to it.
8
public boolean isNew()
This method returns true if the client does not yet know
about the session or if the client chooses not to join the
session.
Servlets Deployment(cont..)
Http Sessions(cont..)
Sr.No. Method & Description
9
public void removeAttribute(String name)
This method removes the object bound with the specified
name from this session.
10
public void setAttribute(String name, Object value)
This method binds an object to this session, using the
name specified.
11
public void setMaxInactiveInterval(int interval)
This method specifies the time, in seconds, between client
requests before the servlet container will invalidate this
session.

More Related Content

DOCX
Core Java Training report
PDF
Spring Boot
PDF
Quizine: An online Test
PPT
Job Portal
DOCX
Project Report on Exam Suite/Test Application/Exam App ( JAVA )
PPTX
Online Quiz System
DOCX
Online Job Portal
DOCX
Job center
Core Java Training report
Spring Boot
Quizine: An online Test
Job Portal
Project Report on Exam Suite/Test Application/Exam App ( JAVA )
Online Quiz System
Online Job Portal
Job center

What's hot (20)

PPTX
Part One: Building Web Apps with the MERN Stack
DOCX
Job portal system doc
PDF
GraalVm and Quarkus
PPTX
Chat server nitish nagar
PDF
Java Training | Java Tutorial for Beginners | Java Programming | Java Certifi...
ODP
Gatling
PPT
Online quiz by danish & sudhanshu techlites
PDF
Spring framework Introduction
PDF
Spring Framework
PDF
online examination portal project presentation
PPTX
Online Quiz System Project PPT
PPTX
Spring Boot and REST API
PPTX
Java project
PPTX
Job portal
PPTX
OCA Java SE 8 Exam Chapter 2 Operators & Statements
PPTX
Node.js Express
PPTX
Quiz application
PDF
Client side scripting
DOCX
Online examination system of open and distance education
PDF
Airline Reservation System - Software Engineering
Part One: Building Web Apps with the MERN Stack
Job portal system doc
GraalVm and Quarkus
Chat server nitish nagar
Java Training | Java Tutorial for Beginners | Java Programming | Java Certifi...
Gatling
Online quiz by danish & sudhanshu techlites
Spring framework Introduction
Spring Framework
online examination portal project presentation
Online Quiz System Project PPT
Spring Boot and REST API
Java project
Job portal
OCA Java SE 8 Exam Chapter 2 Operators & Statements
Node.js Express
Quiz application
Client side scripting
Online examination system of open and distance education
Airline Reservation System - Software Engineering
Ad

Similar to Wt unit 3 (20)

PPTX
servlets sessions and cookies, jdbc connectivity
PPTX
Chapter 3 servlet & jsp
PPTX
SERVLET in web technolgy engineering.pptx
PPT
JAVA Servlets
PPT
PPTX
JAVA SERVLETS acts as a middle layer between a request coming from a web brow...
PPTX
Servlets-UNIT3and introduction to servlet
PPTX
Java Servlet
PDF
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
PPTX
PPTX
SERVLETS (2).pptxintroduction to servlet with all servlets
PPTX
UNIT-3 Servlet
PPTX
Enterprise java unit-1_chapter-3
PPT
Module 4.pptModule 4.pptModule 4.pptModule 4.ppt
PPTX
WEB TECHNOLOGY Unit-3.pptx
PPTX
21CS642 Module 4_1 Servlets PPT.pptx VI SEM CSE Students
PPT
Servlet 01
PPT
Presentation on java servlets
PPTX
Java servlets
PPT
1 java servlets and jsp
servlets sessions and cookies, jdbc connectivity
Chapter 3 servlet & jsp
SERVLET in web technolgy engineering.pptx
JAVA Servlets
JAVA SERVLETS acts as a middle layer between a request coming from a web brow...
Servlets-UNIT3and introduction to servlet
Java Servlet
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
SERVLETS (2).pptxintroduction to servlet with all servlets
UNIT-3 Servlet
Enterprise java unit-1_chapter-3
Module 4.pptModule 4.pptModule 4.pptModule 4.ppt
WEB TECHNOLOGY Unit-3.pptx
21CS642 Module 4_1 Servlets PPT.pptx VI SEM CSE Students
Servlet 01
Presentation on java servlets
Java servlets
1 java servlets and jsp
Ad

Recently uploaded (20)

PDF
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 1)
PDF
Practical Manual AGRO-233 Principles and Practices of Natural Farming
PPTX
Introduction to pro and eukaryotes and differences.pptx
PPTX
20th Century Theater, Methods, History.pptx
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PDF
1.3 FINAL REVISED K-10 PE and Health CG 2023 Grades 4-10 (1).pdf
PPTX
Share_Module_2_Power_conflict_and_negotiation.pptx
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
DOC
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
PDF
My India Quiz Book_20210205121199924.pdf
PDF
Empowerment Technology for Senior High School Guide
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PDF
FOISHS ANNUAL IMPLEMENTATION PLAN 2025.pdf
PDF
ChatGPT for Dummies - Pam Baker Ccesa007.pdf
PPTX
B.Sc. DS Unit 2 Software Engineering.pptx
PDF
Paper A Mock Exam 9_ Attempt review.pdf.
PPTX
Introduction to Building Materials
PPTX
Unit 4 Computer Architecture Multicore Processor.pptx
PDF
Weekly quiz Compilation Jan -July 25.pdf
PDF
advance database management system book.pdf
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 1)
Practical Manual AGRO-233 Principles and Practices of Natural Farming
Introduction to pro and eukaryotes and differences.pptx
20th Century Theater, Methods, History.pptx
Chinmaya Tiranga quiz Grand Finale.pdf
1.3 FINAL REVISED K-10 PE and Health CG 2023 Grades 4-10 (1).pdf
Share_Module_2_Power_conflict_and_negotiation.pptx
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
My India Quiz Book_20210205121199924.pdf
Empowerment Technology for Senior High School Guide
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
FOISHS ANNUAL IMPLEMENTATION PLAN 2025.pdf
ChatGPT for Dummies - Pam Baker Ccesa007.pdf
B.Sc. DS Unit 2 Software Engineering.pptx
Paper A Mock Exam 9_ Attempt review.pdf.
Introduction to Building Materials
Unit 4 Computer Architecture Multicore Processor.pptx
Weekly quiz Compilation Jan -July 25.pdf
advance database management system book.pdf

Wt unit 3

  • 3. Concepts of CGI What is CGI ? The Common Gateway Interface, or CGI, is a set of standards that define how information is exchanged between the web server and a custom script. The Common Gateway Interface, or CGI, is a standard for external gateway programs to interface with information servers such as HTTP servers.
  • 4. Concepts of CGI CGI technology enables the web server to call an external program and pass HTTP request information to the external program to process the request. For each request, it starts a new process.
  • 5. Concepts of CGI CGI Architecture Diagram
  • 6. Disadvantages of CGI There are many problems in CGI technology: 1. If number of clients increases, it takes more time for sending response. 2. For each request, it starts a process and Web server is limited to start processes. 3. It uses platform dependent language e.g. C, C++, perl.
  • 7. Concepts of Servlets What is a Servlet? Servlet can be described in many ways, depending on the context. •Servlet is a technology i.e. used to create web application. •Servlet is an API that provides many interfaces and classes including documentations. •Servlet is an interface that must be implemented for creating any servlet. •Servlet is a class that extend the capabilities of the servers and respond to the incoming request. It can respond to any type of requests. •Servlet is a web component that is deployed on the server to create dynamic web page.
  • 9. Concepts of Servlets Advantage of Servlet There are many advantages of servlet over CGI. The basic benefits of servlet are as follows: •better performance: because it creates a thread for each request not process. •Portability: because it uses java language. •Robust: Servlets are managed by JVM so we don't need to worry about memory leak, garbage collection etc. •Secure: because it uses java language..
  • 10. Concepts of Servlets Advantage of Servlet The web container creates threads for handling the multiple requests to the servlet. Threads have a lot of benefits over the Processes such as they share a common memory area, lightweight, cost of communication between the threads are low.
  • 11. Concepts of Servlets Life Cycle of a Servlet (Servlet Life Cycle) The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the servlet: Servlet class is loaded. Servlet instance is created. init method is invoked. service method is invoked. destroy method is invoked.
  • 12. Concepts of Servlets Life Cycle of a Servlet (Servlet Life Cycle)
  • 13. Concepts of Servlets Servlet Life Cycle methods The init() Method: The init method is called only once. It is called only when the servlet is created, and not called for any user requests afterwards. The init method definition looks like this − public void init() throws ServletException { // Initialization code... }
  • 14. Concepts of Servlets Servlet Life Cycle methods(cont..) The service() Method The service() method is the main method to perform the actual task. The servlet container (i.e. web server) calls the service() method to handle requests coming from the client( browsers) and to write the formatted response back to the client. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
  • 15. Concepts of Servlets Servlet Life Cycle methods(cont..) The service() Method Here is the signature of this method − public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { ….. … } We have nothing to do with service() method but you override either doGet() or doPost() depending on what type of request you receive from the client.
  • 16. Concepts of Servlets Servlet Life Cycle methods(cont..) The destroy() Method The destroy() method is called only once at the end of the life cycle of a servlet. This method gives your servlet a chance to close database connections, halt background threads, write cookie lists or hit counts to disk, and perform other such cleanup activities. public void destroy() { // Finalization code... }
  • 17. Concepts of Servlets Servlet Life Cycle Scenario
  • 18. Sample Code of Servlets //Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; // Extend HttpServlet class public class HelloWorld extends HttpServlet { private String message; public void init() throws ServletException { // Do required initialization message = "Hello World"; } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType("text/html"); // Actual logic goes here. PrintWriter out = response.getWriter(); out.println("<h1>" + message + "</h1>"); } public void destroy() { // do nothing. } }
  • 19. Compiling Servlets Compiling a Servlet: 1. Let us create a file with name HelloWorld.java with the code shown above. 2. Place this file at C:ServletDevel (in Windows) or at /usr/ServletDevel (in Unix). 3. This path location must be added to CLASSPATH before proceeding further. 4. Assuming your environment is setup properly, go in ServletDevel directory and compile HelloWorld.java as follows − $ javac HelloWorld.java
  • 20. Compiling Servlets(con..) 5. If the servlet depends on any other libraries, you have to include those JAR files on your CLASSPATH as well. 6. Include only servlet-api.jar JAR file because if you are not using any other library in Hello World program. 7. If everything goes fine, above compilation would produce HelloWorld.class file in the same directory. Next section would explain how a compiled servlet would be deployed in production.
  • 21. Servlets Deployment Servlet Deployment: Step 1: By default, A servlet application is located at the path <Tomcat-installationdirectory>/webapps/ROOT and the class file would reside in <Tomcat-installationdirectory>/webapps/ROOT/WEB- INF/classes. If you have a fully qualified class name, of com.myorg.MyServlet then this servlet class must be located in WEB-INF/classes/com/myorg/MyServlet.class.
  • 22. Servlets Deployment(con..) Step 2: let us copy HelloWorld.class into <Tomcat-installationdirectory>/webapps/ROOT/WEB- INF/classes Step 3: create following entries in web.xml file located in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/
  • 24. Servlets Deployment(cont..) Step 4: Start tomcat server using <Tomcat-installationdirectory>binstartup.bat (on Windows) or <Tomcat-installationdirectory>/bin/startup.sh (on Linux/Solaris etc.) and Step 5:finally type http://localhost:8080/HelloWorld in the browser's address box.
  • 25. Servlets Deployment(cont..) Servlet API The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet api. The javax.servlet package contains many interfaces and classes that are used by the servlet or web container. These are not specific to any protocol. The javax.servlet.http package contains interfaces and classes that are responsible for http requests only.
  • 26. Servlets Deployment(cont..) There are many interfaces in javax.servlet package. They are as follows: 1. Servlet 2. ServletRequest 3. ServletResponse 4. RequestDispatcher 5. ServletConfig 6. ServletContext 7. SingleThreadModel 8. Filter 9. FilterConfig 10. FilterChain 11. ServletRequestListener 12. ServletRequestAttributeListener 13. ServletContextListener 14. ServletContextAttributeListener
  • 27. Servlets Deployment(cont..) There are many classes in javax.servlet package. They are as follows: 1. GenericServlet 2. ServletInputStream 3. ServletOutputStream 4. ServletRequestWrapper 5. ServletResponseWrapper 6. ServletRequestEvent 7. ServletContextEvent 8. ServletRequestAttributeEvent 9. ServletContextAttributeEvent 10. ServletException 11. UnavailableException
  • 28. Servlets Deployment(cont..) Interfaces in javax.servlet.http package 1. HttpServletRequest 2. HttpServletResponse 3. HttpSession 4. HttpSessionListener 5. HttpSessionAttributeListener 6. HttpSessionBindingListener 7. HttpSessionActivationListener 8. HttpSessionContext (deprecated now)
  • 29. Servlets Deployment(cont..) Classes in javax.servlet.http package 1. HttpServlet 2. Cookie 3. HttpServletRequestWrapper 4. HttpServletResponseWrapper 5. HttpSessionEvent 6. HttpSessionBindingEvent 7. HttpUtils (deprecated now)
  • 30. Servlets Deployment(cont..) Parameters in Servlets The parameters are the way in which a client or user can send information to the Http Server
  • 31. Servlets Deployment(cont..) Parameters in Servlets For example, in a login screen, we need to send to the server, the user and the password so that it validates them.
  • 32. Servlets Deployment(cont..) Parameters in Servlets For example, How does the client or the Browser send these parameters using the methods GET or POST, The first thing we are going to do is to create in our site a page "login.html" with the following content: <html> <body> <form action="login" method="get"> <table> <tr> <td>User</td> <td><input name="user" /></td> </tr> <tr> <td>password</td> <td><input name="password" /></td> </tr> </table> <input type="submit" /> </form> </body> </html>
  • 33. Servlets Deployment(cont..) Parameters in Servlets Then, we create a Servlet which receives the request in /login , which is the indicated direction in the action attribute of the tag <form> of login.html
  • 34. Servlets Deployment(cont..) import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LoginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String user = req.getParameter("user"); String pass = req.getParameter("password"); if ("edu4java".equals(user) && "eli4java".equals(pass)) { response(resp, "login ok"); } else { response(resp, "invalid login"); } }
  • 35. Servlets Deployment(cont..) private void response(HttpServletResponse resp, String msg) throws IOException { PrintWriter out = resp.getWriter(); out.println("<html>"); out.println("<body>"); out.println("<t1>" + msg + "</t1>"); out.println("</body>"); out.println("</html>"); } }
  • 36. Servlets Deployment(cont..) We modify web.xml to link /login with this Servlet. <web-app> <servlet> <servlet-name>timeservlet</servlet-name> <servlet-class>com.edu4java.servlets.FirstServlet</servlet-class> </servlet> <servlet> <servlet-name>login-servlet</servlet-name> <servlet-class>com.edu4java.servlets.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>timeservlet</servlet-name> <url-pattern>/what-time-is-it</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>login-servlet</servlet-name> <url-pattern>/login</url-pattern> </servlet-mapping> </web-app>
  • 37. Servlets Deployment(cont..) Session Tracking and Cookies Session Tracking: Keeping track of a sequence of related requests sent by a client to perform some designated task is known as “Session Tracking” Cookies are one of the solutions to session tracking.
  • 38. Servlets Deployment(cont..) Session Tracking and Cookies(cont..) Cookies: A cookie is a small piece of information that is persisted between the multiple client requests. A cookie has  a name, a single value, and  optional attributes such as a comment, path and  domain qualifiers, a maximum age, and  a version number.
  • 39. Servlets Deployment(cont..) Session Tracking and Cookies(cont..) How Cookies Work:
  • 40. Servlets Deployment(cont..) Session Tracking and Cookies(cont..) How Cookies Work: •By default, each request is considered as a new request. •we add cookie with response from the servlet. •So cookie is stored in the cache of the browser. •After that if request is sent by the user, cookie is added with request by default. •we recognize the user as the old user.
  • 41. Servlets Deployment(cont..) Session Tracking and Cookies(cont..) How Cookies Work: •By default, each request is considered as a new request. •we add cookie with response from the servlet. •So cookie is stored in the cache of the browser. •After that if request is sent by the user, cookie is added with request by default. •we recognize the user as the old user.
  • 42. Servlets Deployment(cont..) Session Tracking and Cookies(cont..) Types of Cookie There are 2 types of cookies in servlets. 1. Non-persistent cookie 2. Persistent cookie Non-persistent cookie It is valid for single session only. It is removed each time when user closes the browser. Persistent cookie It is valid for multiple session . It is not removed each time when user closes the browser. It is removed only if user logout or signout.
  • 43. Servlets Deployment(cont..) Session Tracking and Cookies(cont..) Advantage of Cookies Simplest technique of maintaining the state. Cookies are maintained at client side. Disadvantage of Cookies It will not work if cookie is disabled from the browser. Only textual information can be set in Cookie object.
  • 44. Servlets Deployment(cont..) Session Tracking and Cookies(cont..) Cookie class javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot of useful methods for cookies.
  • 45. Servlets Deployment(cont..) Session Tracking and Cookies(cont..) Constructor of Cookie class Cookie() : constructs a cookie. Cookie(String name, String value) : constructs a cookie with a specified name and value.
  • 46. Servlets Deployment(cont..) Session Tracking and Cookies(cont..) Method Descriptionpublic Public void setMaxAge(int expiry) Sets the maximum age of the cookie in seconds. public String getName() Returns the name of the cookie. The name cannot be changed after creation. public String getValue() Returns the value of the cookie. public void setName(String name) changes the name of the cookie. public void setValue(String value) changes the value of the cookie
  • 47. Servlets Deployment(cont..) Session Tracking and Cookies(cont..) How to send Cookies to the Client( 3 steps ) 1) Create a Cookie object. Cookie c = new Cookie("userName",”Vits"); 2) Set the maximum Age: c.setMaxAge(1800); // value in seconds 3) Place the Cookie in HTTP response header: response.addCookie(c);
  • 48. Servlets Deployment(cont..) Session Tracking and Cookies(cont..) How to Read Cookies from the Client/browser Cookie c[]=request.getCookies(); //c.length gives the cookie count for(int i=0;i<c.length;i++) { out.print("Name: "+c[i].getName()+" & Value: "+c[i].getValue()); }
  • 49. Servlets Deployment(cont..) Session Tracking and Cookies(cont..) How to delete Cookies from the Client/browser If you want to delete a cookie then you simply need to follow up following three steps − Read an already existing cookie and store it in Cookie object. Set cookie age as zero using setMaxAge() method to delete an existing cookie Add this cookie back into response header.
  • 50. Servlets Deployment(cont..) Session Tracking and Cookies(cont..) How to delete Cookies from the Client/browser Let's see the simple code to delete cookie. It is mainly used to logout or sign out the user. Cookie ck=new Cookie("user",""); //deleting value of cookie ck.setMaxAge(0); //changing the maximum age to 0 seconds response.addCookie(ck); //adding cookie in the response
  • 51. Servlets Deployment(cont..) Session Tracking and Cookies(cont..) Http Sessions A session contains information specific to a particular user across the whole application. In such case, container creates a session id for each user. The container uses this id to identify the particular user. This unique ID can be stored into a cookie or in a request parameter. The HttpSession stays alive until it has not been used for more than the timeout value specified in tag in deployment descriptor file. The default timeout value is 30 minutes, this is used if you don’t specify the value in tag.
  • 52. Servlets Deployment(cont..) Session Tracking and Cookies(cont..) Http Sessions(cont..)
  • 53. Servlets Deployment(cont..) Session Tracking and Cookies(cont..) Http Sessions(cont..) This is how you create a HttpSession object. protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { HttpSession session = req.getSession(); }
  • 54. Servlets Deployment(cont..) Http Sessions(cont..) How you can store user information in HttpSession object. setAttribute(): method stores user information session object later when needed this information can be fetched from the session.
  • 55. Servlets Deployment(cont..) Http Sessions(cont..) How you can store user information in HttpSession object. Example: storing username, email-id and user age in session with the attribute name uName, uemailId and uAge respectively. session.setAttribute("uName", "Chaitanya"); session.setAttribute("uemailId", "myemailid@gmail.com"); session.setAttribute("uAge", "30");
  • 56. Servlets Deployment(cont..) Http Sessions(cont..) TO get the value from session we use the getAttribute() method of HttpSession interface. Example: String userName = (String) session.getAttribute("uName"); String userEmailId = (String) session.getAttribute("uemailId"); String userAge = (String) session.getAttribute("uAge");
  • 57. Servlets Deployment(cont..) Http Sessions(cont..) Sr.No. Method & Description 1 public Object getAttribute(String name) This method returns the object bound with the specified name in this session, or null if no object is bound under the name. 2 public Enumeration getAttributeNames() This method returns an Enumeration of String objects containing the names of all the objects bound to this session. 3 public long getCreationTime() This method returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT. 4 public String getId() This method returns a string containing the unique identifier assigned to this session.
  • 58. Servlets Deployment(cont..) Http Sessions(cont..) Sr.No. Method & Description 5 public long getLastAccessedTime() This method returns the last accessed time of the session, in the format of milliseconds since midnight January 1, 1970 GMT 6 public int getMaxInactiveInterval() This method returns the maximum time interval (seconds), that the servlet container will keep the session open between client accesses. 7 public void invalidate() This method invalidates this session and unbinds any objects bound to it. 8 public boolean isNew() This method returns true if the client does not yet know about the session or if the client chooses not to join the session.
  • 59. Servlets Deployment(cont..) Http Sessions(cont..) Sr.No. Method & Description 9 public void removeAttribute(String name) This method removes the object bound with the specified name from this session. 10 public void setAttribute(String name, Object value) This method binds an object to this session, using the name specified. 11 public void setMaxInactiveInterval(int interval) This method specifies the time, in seconds, between client requests before the servlet container will invalidate this session.