SlideShare a Scribd company logo
Java Servlet
Prepared By
Yogaraja C A
Ramco Institute of Technology
Definition
 Servlet technology is used to create a web application
(resides at server side and generates a dynamic web
page).
 Before Servlet, CGI (Common Gateway Interface)
scripting language was common as a server-side
programming language.
 Servlet is an interface that must be implemented for
creating any Servlet.
 Servlet is a class that extends the capabilities of the
servers and responds to the incoming requests. It can
respond to any requests.
Java Servlet
CGI (Common Gateway Interface)
 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.
Disadvantages of CGI
 If the number of clients increases, it takes more
time for sending the response.
 For each request, it starts a process, and the web
server is limited to start processes.
 It uses platform dependent language e.g. C, C++,
perl.
Advantages of Servlet
The web container creates threads for handling the multiple
requests to the Servlet. Threads have many benefits over the
Processes such as they share a common memory area,
lightweight, cost of communication between the threads are
low.
 Better performance: because it creates a thread for
each request, not process.
 Portability: because it uses Java language.
 Robust: JVM manages Servlets, so we don't need to
worry about the memory leak, garbage collection, etc.
 Secure: because it uses java language.
Static vs Dynamic website
Static Website Dynamic Website
Prebuilt content is same every time the page
is loaded.
Content is generated quickly and changes
regularly.
It uses the HTML code for developing a
website.
It uses the server side languages such as
PHP,SERVLET, JSP, and ASP.NET etc. for
developing a website.
It sends exactly the same response for every
request.
It may generate different HTML for each of
the request.
The content is only changed when someone
publishes and updates the file (sends it to the
web server).
The page contains "server-side" code which
allows the server to generate the unique
content when the page is loaded.
Flexibility is the main advantage of static
website.
Content Management System (CMS) is the
main advantage of dynamic website.
Servlet Container
 It provides the runtime environment for JavaEE (j2ee)
applications. The client/user can request only a static WebPages
from the server. If the user wants to read the web pages as per
input then the servlet container is used in java.
 The servlet container is the part of web server which can be run
in a separate process. We can classify the servlet container
states in three types:
Servlet Container States
The servlet container is the part of web server which can be run in a
separate process. We can classify the servlet container states in three
types:
 Standalone: It is typical Java-based servers in which the servlet
container and the web servers are the integral part of a single
program. For example:- Tomcat running by itself
 In-process: It is separated from the web server, because a different
program runs within the address space of the main server as a
plug-in. For example:- Tomcat running inside the JBoss.
 Out-of-process: The web server and servlet container are different
programs which are run in a different process. For performing the
communications between them, web server uses the plug-in
provided by the servlet container.
Servlets - Life Cycle/Architecture
A servlet life cycle can be defined as the entire process
from its creation till the destruction.
 The servlet is initialized by calling the init() method.
 The servlet calls service() method to process a client's
request.
 The servlet is terminated by calling the destroy()
method.
 Finally, servlet is garbage collected by the garbage
collector of the JVM.
Java Servlet
Steps to create a servlet
To create servlet using apache tomcat server, the
steps are as follows:
Create a directory structure
Create a Servlet
Compile the Servlet
Create a deployment descriptor
Start the server and deploy the project
Access the servlet
Create a directory structures
The directory structure defines that where to
put the different types of files so that web
container may get the information and respond
to the client.
The Sun Microsystem defines a unique standard
to be followed by all the server vendors.
Java Servlet
Create a servlet
The servlet example can be created by three ways:
By implementing Servlet interface,
By inheriting GenericServlet class, (or)
By inheriting HttpServlet class
The mostly used approach is by extending HttpServlet
because it provides http request specific method such
as doGet(), doPost(), doHead() etc.
Compile the servlet
For compiling the Servlet, jar file is required to
be loaded. Different Servers provide different
jar files:
jar file Server
servlet-api.jar Apache Tomcat
weblogic.jar Weblogic
javaee.jar Glassfish
javaee.jar JBoss
Create the deployment descriptor (web.xml
file)
The deployment descriptor is an xml file, from
which Web Container gets the information about
the servlet to be invoked.
The web container uses the Parser to get the
information from the web.xml file. There are
many xml parsers such as SAX, DOM and Pull.
There are many elements in the web.xml file. Here
is given some necessary elements to run the
simple servlet program.
Web.xml
<web-app>
<servlet>
<servlet-name>ABC</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ABC</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
Web.xml Description
<web-app> represents the whole application.
<servlet> is sub element of <web-app> and represents
the servlet.
<servlet-name> is sub element of <servlet> represents
the name of the servlet.
<servlet-class> is sub element of <servlet> represents
the class of the servlet.
<servlet-mapping> is sub element of <web-app>. It is
used to map the servlet.
<url-pattern> is sub element of <servlet-mapping>. This
pattern is used at client side to invoke the servlet.
Servlet API
Servlet Interface
 Servlet interface provides common behavior to all the
servlets. Servlet interface defines methods that all
servlets must implement.
 Servlet interface needs to be implemented for creating
any servlet (either directly or indirectly).
 It provides 3 life cycle methods that are used
to initialize the servlet,
to service the requests, and
to destroy the servlet and
2 non-life cycle methods.
Methods of Servlet interface
Method Description
public void init(ServletConfig config)
initializes the servlet. It is the life cycle
method of servlet and invoked by the
web container only once.
public void service(ServletRequest
request,ServletResponse response)
provides response for the incoming
request. It is invoked at each request by
the web container.
public void destroy()
is invoked only once and indicates that
servlet is being destroyed.
public ServletConfig
getServletConfig()
returns the object of ServletConfig.
public String getServletInfo()
returns information about servlet such
as writer, copyright, version etc.
Servlet Example by implementing Servlet interface
public class First implements Servlet {
ServletConfig config=null;
public void init(ServletConfig config){
System.out.println("servlet is initialized"); }
public void service(ServletRequest req,ServletResponse res)
throws IOException,ServletException{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello simple servlet </b>");
out.print("</body></html>"); } }
GenericServlet class
GenericServlet class implements Servlet,
ServletConfig and Serializable interfaces. It provides
the implementation of all the methods of these
interfaces except the service method.
GenericServlet class can handle any type of request
so it is protocol-independent.
You may create a generic servlet by inheriting the
GenericServlet class and providing the
implementation of the service method.
Methods of GenericServlet class
 public void init(ServletConfig config) is used to initialize the servlet.
 public abstract void service(ServletRequest request, ServletResponse
response) provides service for the incoming request. It is invoked at each
time when user requests for a servlet.
 public void destroy() is invoked only once throughout the life cycle and
indicates that servlet is being destroyed.
 public ServletConfig getServletConfig() returns the object of
ServletConfig.
 public String getServletInfo() returns information about servlet such as
writer, copyright, version etc.
 public void init() it is a convenient method for the servlet programmers,
now there is no need to call super.init(config)
 public void log(String msg) writes the given message in the servlet log file.
Servlet by inheriting the GenericServlet class
public class First extends GenericServlet{
public void service(ServletRequest req,ServletResponse res)
throws IOException,ServletException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello generic servlet</b>");
out.print("</body></html>");
}
}
HttpServlet class
The HttpServlet class extends the GenericServlet
class and implements Serializable interface.
It provides http specific methods such as doGet,
doPost, doHead, doTrace etc.
Methods of HttpServlet class
 public void service(ServletRequest req,ServletResponse res) dispatches the
request to the protected service method by converting the request and
response object into http type.
 protected void service(HttpServletRequest req, HttpServletResponse res)
receives the request from the service method, and dispatches the request
to the doXXX() method depending on the incoming http request type.
 protected void doGet(HttpServletRequest req, HttpServletResponse res)
handles the GET request. It is invoked by the web container.
 protected void doPost(HttpServletRequest req, HttpServletResponse res)
handles the POST request. It is invoked by the web container.
 protected void doHead(HttpServletRequest req, HttpServletResponse res)
handles the HEAD request. It is invoked by the web container.
Methods of HttpServlet class
 protected void doOptions(HttpServletRequest req,
HttpServletResponse res) handles the OPTIONS request. It is invoked by
the web container.
 protected void doPut(HttpServletRequest req, HttpServletResponse
res) handles the PUT request. It is invoked by the web container.
 protected void doTrace(HttpServletRequest req, HttpServletResponse
res) handles the TRACE request. It is invoked by the web container.
 protected void doDelete(HttpServletRequest req, HttpServletResponse
res) handles the DELETE request. It is invoked by the web container.
 protected long getLastModified(HttpServletRequest req) returns the
time when HttpServletRequest was last modified since midnight January
1, 1970 GMT.
Servlet by inheriting the HttpServlet class
public class First extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
pw.println("<html><body>");
pw.println("Welcome to servlet");
pw.println("</body></html>");
pw.close();
}}
Working of Servlet
How Servlet works?
 The server checks if the servlet is requested for the first time.
 If yes, web container does the following tasks:
loads the servlet class.
instantiates the servlet class.
calls the init method passing the ServletConfig object
 else
calls the service method passing request and response
objects
The web container calls the destroy method when it needs to
remove the servlet such as at time of stopping server or
undeploying the project.
How web container handles the servlet request?
The web container is responsible to handle the request.
 maps the request with the servlet in the web.xml file.
 creates request and response objects for this request
 calls the service method on the thread
 The public service method internally calls the protected service method
 The protected service method calls the doGet method depending on the
type of request.
 The doGet method generates the response and it is passed to the client.
 After sending the response, the web container deletes the request and
response objects. The thread is contained in the thread pool or deleted
depends on the server implementation.
What is written inside the public service
method?
The public service method converts the
ServletRequest object into the
HttpServletRequest type and ServletResponse
object into the HttpServletResponse type.
Then, calls the service method passing these
objects.
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException
{
HttpServletRequest request;
HttpServletResponse response;
try { request = (HttpServletRequest)req; response = (HttpServletResponse)res;
}
catch(ClassCastException e)
{ throw new ServletException("non-HTTP request or response");
}
service(request, response);
}
What is written inside the protected service
method?
The protected service method checks the type
of request, if request type is get, it calls doGet
method, if request type is post, it calls doPost
method, so on.
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
String method = req.getMethod();
if(method.equals("GET"))
{
long lastModified = getLastModified(req);
if(lastModified == -1L)
{
doGet(req, resp);
} //POST Code goes here
} }
Invoking Servlet From
HTML using GenericServlet
Invoking Servlet From HTML(index.html)
<html>
<head> <TITLE>INVOKING SERVLET FROM HTML </TITLE> </head>
<BODY> <FORM name = "PostParam" method = "Post" action="Server">
<TABLE> <tr>
<td> <B>Employee: </B> </td>
<td><input type = "textbox" name="ename" size="25“ value=""></td>
</tr> </TABLE>
<INPUT type = "submit" value="Submit">
</FORM>
</body>
</html>
Invoking Servlet From HTML(Server.java)
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/Server")
public class Server extends GenericServlet {
public void service(ServletRequest request,ServletResponse response)throws
ServletException,IOException
{ PrintWriter out=response.getWriter();
String name=request.getParameter("ename");
out.println("EmployeeName: "+name);
} }
Invoking Servlet From HTML(web.xml)
<?xml version="1.0" encoding="UTF-8"?>
<element> <web-app>
<display-name>invokehtml</display-name>
<servlet> <servlet-name>as</servlet-name>
<servlet-class>Server</servlet-class> </servlet>
<servlet-mapping> <servlet-name>as</servlet-name>
<url-pattern>/Server</url-pattern> </servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app> </element>
Invoking Servlet From
HTML using HttpServlet
Invoking Servlet From HTML(index.html)
<html>
<head> <TITLE>INVOKING SERVLET FROM HTML </TITLE> </head>
<BODY> <FORM name = "PostParam" method = “get" action="Server">
<TABLE> <tr>
<td> <B>Employee: </B> </td>
<td><input type = "textbox" name="ename" size="25“ value=""></td>
</tr> </TABLE>
<INPUT type = "submit" value="Submit">
</FORM>
</body>
</html>
Invoking Servlet From HTML (Server.java)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/Server")
public class Server extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse
response)throws ServletException,IOException
{ PrintWriter out=response.getWriter();
String name=request.getParameter("ename");
out.println("EmployeeNa: "+name); } }
Invoking Servlet From HTML(web.xml)
<?xml version="1.0" encoding="UTF-8"?>
<element> <web-app>
<display-name>invokehtml</display-name>
<servlet> <servlet-name>as</servlet-name>
<servlet-class>Server</servlet-class> </servlet>
<servlet-mapping> <servlet-name>as</servlet-name>
<url-pattern>/Server</url-pattern> </servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app> </element>
Session
Tracking/Handling
in Servlets
Introduction
 Session simply means a particular interval of time.
 Session Tracking is a way to maintain state (data) of
an user. It is also known as session management in
servlet.
 Http protocol is a stateless so we need to maintain
state using session tracking techniques. Each time
user requests to the server, server treats the request
as the new request. So we need to maintain the state
of an user to recognize to particular user.
Introduction
 HTTP is stateless that means each request is
considered as the new request. It is shown in the
figure given below:
Why use Session Tracking?
 To recognize the user It is used to recognize the
particular user.
Session Tracking Techniques
There are four techniques used in Session
tracking:
Cookies
Hidden Form Field
URL Rewriting
HttpSession
Cookies in Servlet
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.
How Cookie works
 By default, each request is considered as a new request.
 In cookies technique, 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.
 Thus, we recognize the user as the old user.
How Cookie works
Types of Cookie
There are 2 types of cookies in servlets.
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.
Advantage/Disadvantage of Cookies
Advantage
Simplest technique of maintaining the state.
Cookies are maintained at client side.
Disadvantage
It will not work if cookie is disabled from the
browser.
Only textual information can be set in Cookie object.
Methods of Cookie class
 javax.servlet.http.Cookie class provides the
functionality of using cookies. It provides a lot of useful
methods for cookies.
Method Description
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.
How to create Cookie?
//creating cookie object
Cookie c=new Cookie("user",“Newton");
//adding cookie in the response
response.addCookie(c);
How to delete Cookie?
//deleting value of cookie
Cookie c=new Cookie("user","");
//changing the maximum age to 0 seconds
c.setMaxAge(0);
//adding cookie in the response
response.addCookie(c);
How to get Cookies?
Cookie c[]=request.getCookies();
for(int i=0;i<c.length;i++)
{
out.print("<br>"+c[i].getName()+" "+c[i].getValue());
}
Simple example of Servlet Cookies
Index.html
<form action="servlet1" method="post">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
Cookie ck=new Cookie("uname",n);//creating cookie object
response.addCookie(ck);//adding cookie in the response
out.print("<form action='servlet2‘ method=‘post’>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();
}catch(Exception e){System.out.println(e); } }
SecondServlet.java
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());
out.close();
}catch(Exception e){
System.out.println(e); } }
web.xml
<web-app>
<servlet> <servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class> </servlet>
<servlet-mapping> <servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern> </servlet-mapping>
<servlet> <servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class> </servlet>
<servlet-mapping> <servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern> </servlet-mapping>
</web-app>
Hidden Form Field
 In case of Hidden Form Field a hidden (invisible) textfield
is used for maintaining the state of an user.
 In such case, we store the information in the hidden field
and get it from another servlet. This approach is better if
we have to submit form in all the pages and we don't
want to depend on the browser.
 It is widely used in comment form of a website to store
page id or page name in the hidden field so that each
page can be uniquely identified.
 code to store value in hidden field
<input type="hidden" name="uname" value="Vimal ">
Advantage/Disadvantage of Hidden Form Fields
Advantage
It will always work whether cookie is disabled or not.
Disadvantage
It is maintained at server side.
Extra form submission is required on each pages.
Only textual information can be used.
Index.html
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
out.print("<form action='servlet2‘ method=‘post’>");
out.print("<input type='hidden' name='uname' value='"+n+"'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();
}catch(Exception e){System.out.println(e); } }
SecondServlet.java
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e){
System.out.println(e); } }
web.xml
<web-app>
<servlet> <servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class> </servlet>
<servlet-mapping> <servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern> </servlet-mapping>
<servlet> <servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class> </servlet>
<servlet-mapping> <servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern> </servlet-mapping>
</web-app>
URL Rewriting
 In URL rewriting, we append a token or identifier to the URL of the
next Servlet or the next resource.
 We can send parameter name/value pairs using the following format:
url?name1=value1&name2=value2&??
 A name and a value is separated using an equal = sign,
 A parameter name/value pair is separated from another parameter
using the ampersand(&).
 When the user clicks the hyperlink, the parameter name/value pairs
will be passed to the server.
 From a Servlet, we can use getParameter() method to obtain a
parameter value.
Advantage/Disadvantage of URL Rewriting
Advantage
It will always work whether cookie is disabled or not
(browser independent).
Extra form submission is not required on each pages.
Disadvantage
It will work only with links.
It can send Only textual information.
Index.html
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
out.print("<a href='servlet2?uname="+n+"'>visit</a>");
out.close();
}catch(Exception e){System.out.println(e); } }
SecondServlet.java
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e){
System.out.println(e); } }
web.xml
<web-app>
<servlet> <servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class> </servlet>
<servlet-mapping> <servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern> </servlet-mapping>
<servlet> <servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class> </servlet>
<servlet-mapping> <servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern> </servlet-mapping>
</web-app>
HttpSession interface
Container creates a session id for each user. The
container uses this id to identify the particular user.
An object of HttpSession can be used to perform
two tasks:
bind objects
view and manipulate information about a session, such
as the session identifier, creation time, and last
accessed time.
HttpSession interface
How to get the HttpSession object ?
The HttpServletRequest interface provides two
methods to get the object of HttpSession:
public HttpSession getSession():Returns the current
session associated with this request, or if the request
does not have a session, creates one.
public HttpSession getSession(boolean
create):Returns the current HttpSession associated
with this request or, if there is no current session and
create is true, returns a new session.
Methods of HttpSession interface
 public String getId():Returns a string containing the
unique identifier value.
 public long getCreationTime():Returns the time when
this session was created, measured in milliseconds since
midnight January 1, 1970 GMT.
 public long getLastAccessedTime():Returns the last time
the client sent a request associated with this session, as
the number of milliseconds since midnight January 1,
1970 GMT.
 public void invalidate():Invalidates this session then
unbinds any objects bound to it.
Index.html
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
HttpSession session=request.getSession();
session.setAttribute("uname",n);
out.print("<a href='servlet2'>visit</a>");
out.close();
}catch(Exception e){System.out.println(e); } }
SecondServlet.java
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session=request.getSession(false);
String n=request.getParameter("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e){
System.out.println(e); } }
web.xml
<web-app>
<servlet> <servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class> </servlet>
<servlet-mapping> <servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern> </servlet-mapping>
<servlet> <servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class> </servlet>
<servlet-mapping> <servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern> </servlet-mapping>
</web-app>

More Related Content

What's hot (20)

PPTX
JAVA AWT
shanmuga rajan
 
PPT
Java servlet life cycle - methods ppt
kamal kotecha
 
PPTX
Awt
Rakesh Patil
 
PDF
Web Technologies Notes - TutorialsDuniya.pdf
Raghunathan52
 
PPTX
QSpiders - Jdk Jvm Jre and Jit
Qspiders - Software Testing Training Institute
 
PPTX
ASP.NET WEB API
Thang Chung
 
PPT
Looping statements in Java
Jin Castor
 
PPTX
SQL: Creating and Altering Tables
RJ Podeschi
 
PDF
Servlet and servlet life cycle
Dhruvin Nakrani
 
PDF
Introduction to Node.js
Rob O'Doherty
 
PPT
Java awt
Arati Gadgil
 
PPTX
Web technologies lesson 1
nhepner
 
PPT
C# basics
Dinesh kumar
 
PPT
Visual Studio IDE
Sayantan Sur
 
PPTX
Java string handling
Salman Khan
 
PDF
Collections Api - Java
Drishti Bhalla
 
PPTX
Validation Controls in asp.net
Deep Patel
 
DOCX
Autoboxing and unboxing
Geetha Manohar
 
PDF
Array
Ravi_Kant_Sahu
 
PPTX
Event Handling in java
Google
 
JAVA AWT
shanmuga rajan
 
Java servlet life cycle - methods ppt
kamal kotecha
 
Web Technologies Notes - TutorialsDuniya.pdf
Raghunathan52
 
QSpiders - Jdk Jvm Jre and Jit
Qspiders - Software Testing Training Institute
 
ASP.NET WEB API
Thang Chung
 
Looping statements in Java
Jin Castor
 
SQL: Creating and Altering Tables
RJ Podeschi
 
Servlet and servlet life cycle
Dhruvin Nakrani
 
Introduction to Node.js
Rob O'Doherty
 
Java awt
Arati Gadgil
 
Web technologies lesson 1
nhepner
 
C# basics
Dinesh kumar
 
Visual Studio IDE
Sayantan Sur
 
Java string handling
Salman Khan
 
Collections Api - Java
Drishti Bhalla
 
Validation Controls in asp.net
Deep Patel
 
Autoboxing and unboxing
Geetha Manohar
 
Event Handling in java
Google
 

Similar to Java Servlet (20)

PPTX
SERVLET in web technolgy engineering.pptx
ARUNKUMARM230658
 
PPTX
Wt unit 3
team11vgnt
 
PPT
JAVA Servlets
deepak kumar
 
PPT
Servlets
Sasidhar Kothuru
 
PPTX
SERVLETS (2).pptxintroduction to servlet with all servlets
RadhikaP41
 
PPTX
Chapter 3 servlet & jsp
Jafar Nesargi
 
PPT
1 java servlets and jsp
Ankit Minocha
 
DOC
Unit5 servlets
Praveen Yadav
 
PPTX
21CS642 Module 4_1 Servlets PPT.pptx VI SEM CSE Students
VENKATESHBHAT25
 
PPTX
Server side programming
javed ahmed
 
PDF
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Tushar B Kute
 
PPTX
java Servlet technology
Tanmoy Barman
 
PPT
Servlet ppt by vikas jagtap
Vikas Jagtap
 
PPT
Servlet 01
Bharat777
 
PPTX
servlets sessions and cookies, jdbc connectivity
snehalatha790700
 
PDF
Java servlet technology
Minal Maniar
 
PPTX
ADP - Chapter 2 Exploring the java Servlet Technology
Riza Nurman
 
PPTX
Enterprise java unit-1_chapter-3
sandeep54552
 
PPTX
Servlets
Akshay Ballarpure
 
PDF
SERVER SIDE PROGRAMMING
Prabu U
 
SERVLET in web technolgy engineering.pptx
ARUNKUMARM230658
 
Wt unit 3
team11vgnt
 
JAVA Servlets
deepak kumar
 
SERVLETS (2).pptxintroduction to servlet with all servlets
RadhikaP41
 
Chapter 3 servlet & jsp
Jafar Nesargi
 
1 java servlets and jsp
Ankit Minocha
 
Unit5 servlets
Praveen Yadav
 
21CS642 Module 4_1 Servlets PPT.pptx VI SEM CSE Students
VENKATESHBHAT25
 
Server side programming
javed ahmed
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Tushar B Kute
 
java Servlet technology
Tanmoy Barman
 
Servlet ppt by vikas jagtap
Vikas Jagtap
 
Servlet 01
Bharat777
 
servlets sessions and cookies, jdbc connectivity
snehalatha790700
 
Java servlet technology
Minal Maniar
 
ADP - Chapter 2 Exploring the java Servlet Technology
Riza Nurman
 
Enterprise java unit-1_chapter-3
sandeep54552
 
SERVER SIDE PROGRAMMING
Prabu U
 
Ad

More from Yoga Raja (10)

PPTX
Ajax
Yoga Raja
 
PPTX
Php
Yoga Raja
 
PPTX
Xml
Yoga Raja
 
PPTX
Database connect
Yoga Raja
 
PPTX
JSP- JAVA SERVER PAGES
Yoga Raja
 
PPTX
JSON
Yoga Raja
 
PDF
Java script
Yoga Raja
 
DOCX
Think-Pair-Share
Yoga Raja
 
DOCX
Minute paper
Yoga Raja
 
PPTX
Decision support system-MIS
Yoga Raja
 
Ajax
Yoga Raja
 
Database connect
Yoga Raja
 
JSP- JAVA SERVER PAGES
Yoga Raja
 
JSON
Yoga Raja
 
Java script
Yoga Raja
 
Think-Pair-Share
Yoga Raja
 
Minute paper
Yoga Raja
 
Decision support system-MIS
Yoga Raja
 
Ad

Recently uploaded (20)

PPTX
Introduction to Biochemistry & Cellular Foundations.pptx
marvinnbustamante1
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PDF
epi editorial commitee meeting presentation
MIPLM
 
PPTX
How to Send Email From Odoo 18 Website - Odoo Slides
Celine George
 
PDF
Vani - The Voice of Excellence - Jul 2025 issue
Savipriya Raghavendra
 
PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PDF
Introduction presentation of the patentbutler tool
MIPLM
 
PDF
Is Assignment Help Legal in Australia_.pdf
thomas19williams83
 
PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PPTX
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
PDF
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
PPTX
TRANSLATIONAL AND ROTATIONAL MOTION.pptx
KIPAIZAGABAWA1
 
PPTX
Controller Request and Response in Odoo18
Celine George
 
PDF
Governor Josh Stein letter to NC delegation of U.S. House
Mebane Rash
 
PDF
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
PDF
Characteristics, Strengths and Weaknesses of Quantitative Research.pdf
Thelma Villaflores
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PPTX
Nitrogen rule, ring rule, mc lafferty.pptx
nbisen2001
 
PDF
Council of Chalcedon Re-Examined
Smiling Lungs
 
PPTX
Introduction to Indian Writing in English
Trushali Dodiya
 
Introduction to Biochemistry & Cellular Foundations.pptx
marvinnbustamante1
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
epi editorial commitee meeting presentation
MIPLM
 
How to Send Email From Odoo 18 Website - Odoo Slides
Celine George
 
Vani - The Voice of Excellence - Jul 2025 issue
Savipriya Raghavendra
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
Introduction presentation of the patentbutler tool
MIPLM
 
Is Assignment Help Legal in Australia_.pdf
thomas19williams83
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
TRANSLATIONAL AND ROTATIONAL MOTION.pptx
KIPAIZAGABAWA1
 
Controller Request and Response in Odoo18
Celine George
 
Governor Josh Stein letter to NC delegation of U.S. House
Mebane Rash
 
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
Characteristics, Strengths and Weaknesses of Quantitative Research.pdf
Thelma Villaflores
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
Nitrogen rule, ring rule, mc lafferty.pptx
nbisen2001
 
Council of Chalcedon Re-Examined
Smiling Lungs
 
Introduction to Indian Writing in English
Trushali Dodiya
 

Java Servlet

  • 1. Java Servlet Prepared By Yogaraja C A Ramco Institute of Technology
  • 2. Definition  Servlet technology is used to create a web application (resides at server side and generates a dynamic web page).  Before Servlet, CGI (Common Gateway Interface) scripting language was common as a server-side programming language.  Servlet is an interface that must be implemented for creating any Servlet.  Servlet is a class that extends the capabilities of the servers and responds to the incoming requests. It can respond to any requests.
  • 4. CGI (Common Gateway Interface)  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. Disadvantages of CGI  If the number of clients increases, it takes more time for sending the response.  For each request, it starts a process, and the web server is limited to start processes.  It uses platform dependent language e.g. C, C++, perl.
  • 6. Advantages of Servlet The web container creates threads for handling the multiple requests to the Servlet. Threads have many benefits over the Processes such as they share a common memory area, lightweight, cost of communication between the threads are low.  Better performance: because it creates a thread for each request, not process.  Portability: because it uses Java language.  Robust: JVM manages Servlets, so we don't need to worry about the memory leak, garbage collection, etc.  Secure: because it uses java language.
  • 7. Static vs Dynamic website Static Website Dynamic Website Prebuilt content is same every time the page is loaded. Content is generated quickly and changes regularly. It uses the HTML code for developing a website. It uses the server side languages such as PHP,SERVLET, JSP, and ASP.NET etc. for developing a website. It sends exactly the same response for every request. It may generate different HTML for each of the request. The content is only changed when someone publishes and updates the file (sends it to the web server). The page contains "server-side" code which allows the server to generate the unique content when the page is loaded. Flexibility is the main advantage of static website. Content Management System (CMS) is the main advantage of dynamic website.
  • 8. Servlet Container  It provides the runtime environment for JavaEE (j2ee) applications. The client/user can request only a static WebPages from the server. If the user wants to read the web pages as per input then the servlet container is used in java.  The servlet container is the part of web server which can be run in a separate process. We can classify the servlet container states in three types:
  • 9. Servlet Container States The servlet container is the part of web server which can be run in a separate process. We can classify the servlet container states in three types:  Standalone: It is typical Java-based servers in which the servlet container and the web servers are the integral part of a single program. For example:- Tomcat running by itself  In-process: It is separated from the web server, because a different program runs within the address space of the main server as a plug-in. For example:- Tomcat running inside the JBoss.  Out-of-process: The web server and servlet container are different programs which are run in a different process. For performing the communications between them, web server uses the plug-in provided by the servlet container.
  • 10. Servlets - Life Cycle/Architecture A servlet life cycle can be defined as the entire process from its creation till the destruction.  The servlet is initialized by calling the init() method.  The servlet calls service() method to process a client's request.  The servlet is terminated by calling the destroy() method.  Finally, servlet is garbage collected by the garbage collector of the JVM.
  • 12. Steps to create a servlet To create servlet using apache tomcat server, the steps are as follows: Create a directory structure Create a Servlet Compile the Servlet Create a deployment descriptor Start the server and deploy the project Access the servlet
  • 13. Create a directory structures The directory structure defines that where to put the different types of files so that web container may get the information and respond to the client. The Sun Microsystem defines a unique standard to be followed by all the server vendors.
  • 15. Create a servlet The servlet example can be created by three ways: By implementing Servlet interface, By inheriting GenericServlet class, (or) By inheriting HttpServlet class The mostly used approach is by extending HttpServlet because it provides http request specific method such as doGet(), doPost(), doHead() etc.
  • 16. Compile the servlet For compiling the Servlet, jar file is required to be loaded. Different Servers provide different jar files: jar file Server servlet-api.jar Apache Tomcat weblogic.jar Weblogic javaee.jar Glassfish javaee.jar JBoss
  • 17. Create the deployment descriptor (web.xml file) The deployment descriptor is an xml file, from which Web Container gets the information about the servlet to be invoked. The web container uses the Parser to get the information from the web.xml file. There are many xml parsers such as SAX, DOM and Pull. There are many elements in the web.xml file. Here is given some necessary elements to run the simple servlet program.
  • 19. Web.xml Description <web-app> represents the whole application. <servlet> is sub element of <web-app> and represents the servlet. <servlet-name> is sub element of <servlet> represents the name of the servlet. <servlet-class> is sub element of <servlet> represents the class of the servlet. <servlet-mapping> is sub element of <web-app>. It is used to map the servlet. <url-pattern> is sub element of <servlet-mapping>. This pattern is used at client side to invoke the servlet.
  • 21. Servlet Interface  Servlet interface provides common behavior to all the servlets. Servlet interface defines methods that all servlets must implement.  Servlet interface needs to be implemented for creating any servlet (either directly or indirectly).  It provides 3 life cycle methods that are used to initialize the servlet, to service the requests, and to destroy the servlet and 2 non-life cycle methods.
  • 22. Methods of Servlet interface Method Description public void init(ServletConfig config) initializes the servlet. It is the life cycle method of servlet and invoked by the web container only once. public void service(ServletRequest request,ServletResponse response) provides response for the incoming request. It is invoked at each request by the web container. public void destroy() is invoked only once and indicates that servlet is being destroyed. public ServletConfig getServletConfig() returns the object of ServletConfig. public String getServletInfo() returns information about servlet such as writer, copyright, version etc.
  • 23. Servlet Example by implementing Servlet interface public class First implements Servlet { ServletConfig config=null; public void init(ServletConfig config){ System.out.println("servlet is initialized"); } public void service(ServletRequest req,ServletResponse res) throws IOException,ServletException{ res.setContentType("text/html"); PrintWriter out=res.getWriter(); out.print("<html><body>"); out.print("<b>hello simple servlet </b>"); out.print("</body></html>"); } }
  • 24. GenericServlet class GenericServlet class implements Servlet, ServletConfig and Serializable interfaces. It provides the implementation of all the methods of these interfaces except the service method. GenericServlet class can handle any type of request so it is protocol-independent. You may create a generic servlet by inheriting the GenericServlet class and providing the implementation of the service method.
  • 25. Methods of GenericServlet class  public void init(ServletConfig config) is used to initialize the servlet.  public abstract void service(ServletRequest request, ServletResponse response) provides service for the incoming request. It is invoked at each time when user requests for a servlet.  public void destroy() is invoked only once throughout the life cycle and indicates that servlet is being destroyed.  public ServletConfig getServletConfig() returns the object of ServletConfig.  public String getServletInfo() returns information about servlet such as writer, copyright, version etc.  public void init() it is a convenient method for the servlet programmers, now there is no need to call super.init(config)  public void log(String msg) writes the given message in the servlet log file.
  • 26. Servlet by inheriting the GenericServlet class public class First extends GenericServlet{ public void service(ServletRequest req,ServletResponse res) throws IOException,ServletException { res.setContentType("text/html"); PrintWriter out=res.getWriter(); out.print("<html><body>"); out.print("<b>hello generic servlet</b>"); out.print("</body></html>"); } }
  • 27. HttpServlet class The HttpServlet class extends the GenericServlet class and implements Serializable interface. It provides http specific methods such as doGet, doPost, doHead, doTrace etc.
  • 28. Methods of HttpServlet class  public void service(ServletRequest req,ServletResponse res) dispatches the request to the protected service method by converting the request and response object into http type.  protected void service(HttpServletRequest req, HttpServletResponse res) receives the request from the service method, and dispatches the request to the doXXX() method depending on the incoming http request type.  protected void doGet(HttpServletRequest req, HttpServletResponse res) handles the GET request. It is invoked by the web container.  protected void doPost(HttpServletRequest req, HttpServletResponse res) handles the POST request. It is invoked by the web container.  protected void doHead(HttpServletRequest req, HttpServletResponse res) handles the HEAD request. It is invoked by the web container.
  • 29. Methods of HttpServlet class  protected void doOptions(HttpServletRequest req, HttpServletResponse res) handles the OPTIONS request. It is invoked by the web container.  protected void doPut(HttpServletRequest req, HttpServletResponse res) handles the PUT request. It is invoked by the web container.  protected void doTrace(HttpServletRequest req, HttpServletResponse res) handles the TRACE request. It is invoked by the web container.  protected void doDelete(HttpServletRequest req, HttpServletResponse res) handles the DELETE request. It is invoked by the web container.  protected long getLastModified(HttpServletRequest req) returns the time when HttpServletRequest was last modified since midnight January 1, 1970 GMT.
  • 30. Servlet by inheriting the HttpServlet class public class First extends HttpServlet{ public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { res.setContentType("text/html"); PrintWriter pw=res.getWriter(); pw.println("<html><body>"); pw.println("Welcome to servlet"); pw.println("</body></html>"); pw.close(); }}
  • 32. How Servlet works?  The server checks if the servlet is requested for the first time.  If yes, web container does the following tasks: loads the servlet class. instantiates the servlet class. calls the init method passing the ServletConfig object  else calls the service method passing request and response objects The web container calls the destroy method when it needs to remove the servlet such as at time of stopping server or undeploying the project.
  • 33. How web container handles the servlet request? The web container is responsible to handle the request.  maps the request with the servlet in the web.xml file.  creates request and response objects for this request  calls the service method on the thread  The public service method internally calls the protected service method  The protected service method calls the doGet method depending on the type of request.  The doGet method generates the response and it is passed to the client.  After sending the response, the web container deletes the request and response objects. The thread is contained in the thread pool or deleted depends on the server implementation.
  • 34. What is written inside the public service method? The public service method converts the ServletRequest object into the HttpServletRequest type and ServletResponse object into the HttpServletResponse type. Then, calls the service method passing these objects.
  • 35. public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { HttpServletRequest request; HttpServletResponse response; try { request = (HttpServletRequest)req; response = (HttpServletResponse)res; } catch(ClassCastException e) { throw new ServletException("non-HTTP request or response"); } service(request, response); }
  • 36. What is written inside the protected service method? The protected service method checks the type of request, if request type is get, it calls doGet method, if request type is post, it calls doPost method, so on.
  • 37. protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String method = req.getMethod(); if(method.equals("GET")) { long lastModified = getLastModified(req); if(lastModified == -1L) { doGet(req, resp); } //POST Code goes here } }
  • 38. Invoking Servlet From HTML using GenericServlet
  • 39. Invoking Servlet From HTML(index.html) <html> <head> <TITLE>INVOKING SERVLET FROM HTML </TITLE> </head> <BODY> <FORM name = "PostParam" method = "Post" action="Server"> <TABLE> <tr> <td> <B>Employee: </B> </td> <td><input type = "textbox" name="ename" size="25“ value=""></td> </tr> </TABLE> <INPUT type = "submit" value="Submit"> </FORM> </body> </html>
  • 40. Invoking Servlet From HTML(Server.java) import java.io.*; import javax.servlet.*; import javax.servlet.annotation.WebServlet; @WebServlet("/Server") public class Server extends GenericServlet { public void service(ServletRequest request,ServletResponse response)throws ServletException,IOException { PrintWriter out=response.getWriter(); String name=request.getParameter("ename"); out.println("EmployeeName: "+name); } }
  • 41. Invoking Servlet From HTML(web.xml) <?xml version="1.0" encoding="UTF-8"?> <element> <web-app> <display-name>invokehtml</display-name> <servlet> <servlet-name>as</servlet-name> <servlet-class>Server</servlet-class> </servlet> <servlet-mapping> <servlet-name>as</servlet-name> <url-pattern>/Server</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app> </element>
  • 42. Invoking Servlet From HTML using HttpServlet
  • 43. Invoking Servlet From HTML(index.html) <html> <head> <TITLE>INVOKING SERVLET FROM HTML </TITLE> </head> <BODY> <FORM name = "PostParam" method = “get" action="Server"> <TABLE> <tr> <td> <B>Employee: </B> </td> <td><input type = "textbox" name="ename" size="25“ value=""></td> </tr> </TABLE> <INPUT type = "submit" value="Submit"> </FORM> </body> </html>
  • 44. Invoking Servlet From HTML (Server.java) import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.annotation.WebServlet; @WebServlet("/Server") public class Server extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException { PrintWriter out=response.getWriter(); String name=request.getParameter("ename"); out.println("EmployeeNa: "+name); } }
  • 45. Invoking Servlet From HTML(web.xml) <?xml version="1.0" encoding="UTF-8"?> <element> <web-app> <display-name>invokehtml</display-name> <servlet> <servlet-name>as</servlet-name> <servlet-class>Server</servlet-class> </servlet> <servlet-mapping> <servlet-name>as</servlet-name> <url-pattern>/Server</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app> </element>
  • 47. Introduction  Session simply means a particular interval of time.  Session Tracking is a way to maintain state (data) of an user. It is also known as session management in servlet.  Http protocol is a stateless so we need to maintain state using session tracking techniques. Each time user requests to the server, server treats the request as the new request. So we need to maintain the state of an user to recognize to particular user.
  • 48. Introduction  HTTP is stateless that means each request is considered as the new request. It is shown in the figure given below: Why use Session Tracking?  To recognize the user It is used to recognize the particular user.
  • 49. Session Tracking Techniques There are four techniques used in Session tracking: Cookies Hidden Form Field URL Rewriting HttpSession
  • 50. Cookies in Servlet 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.
  • 51. How Cookie works  By default, each request is considered as a new request.  In cookies technique, 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.  Thus, we recognize the user as the old user.
  • 53. Types of Cookie There are 2 types of cookies in servlets. 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.
  • 54. Advantage/Disadvantage of Cookies Advantage Simplest technique of maintaining the state. Cookies are maintained at client side. Disadvantage It will not work if cookie is disabled from the browser. Only textual information can be set in Cookie object.
  • 55. Methods of Cookie class  javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot of useful methods for cookies. Method Description 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.
  • 56. How to create Cookie? //creating cookie object Cookie c=new Cookie("user",“Newton"); //adding cookie in the response response.addCookie(c);
  • 57. How to delete Cookie? //deleting value of cookie Cookie c=new Cookie("user",""); //changing the maximum age to 0 seconds c.setMaxAge(0); //adding cookie in the response response.addCookie(c);
  • 58. How to get Cookies? Cookie c[]=request.getCookies(); for(int i=0;i<c.length;i++) { out.print("<br>"+c[i].getName()+" "+c[i].getValue()); }
  • 59. Simple example of Servlet Cookies
  • 60. Index.html <form action="servlet1" method="post"> Name:<input type="text" name="userName"/><br/> <input type="submit" value="go"/> </form>
  • 61. FirstServlet.java try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("userName"); out.print("Welcome "+n); Cookie ck=new Cookie("uname",n);//creating cookie object response.addCookie(ck);//adding cookie in the response out.print("<form action='servlet2‘ method=‘post’>"); out.print("<input type='submit' value='go'>"); out.print("</form>"); out.close(); }catch(Exception e){System.out.println(e); } }
  • 62. SecondServlet.java try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); Cookie ck[]=request.getCookies(); out.print("Hello "+ck[0].getValue()); out.close(); }catch(Exception e){ System.out.println(e); } }
  • 63. web.xml <web-app> <servlet> <servlet-name>s1</servlet-name> <servlet-class>FirstServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>/servlet1</url-pattern> </servlet-mapping> <servlet> <servlet-name>s2</servlet-name> <servlet-class>SecondServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s2</servlet-name> <url-pattern>/servlet2</url-pattern> </servlet-mapping> </web-app>
  • 64. Hidden Form Field  In case of Hidden Form Field a hidden (invisible) textfield is used for maintaining the state of an user.  In such case, we store the information in the hidden field and get it from another servlet. This approach is better if we have to submit form in all the pages and we don't want to depend on the browser.  It is widely used in comment form of a website to store page id or page name in the hidden field so that each page can be uniquely identified.  code to store value in hidden field <input type="hidden" name="uname" value="Vimal ">
  • 65. Advantage/Disadvantage of Hidden Form Fields Advantage It will always work whether cookie is disabled or not. Disadvantage It is maintained at server side. Extra form submission is required on each pages. Only textual information can be used.
  • 66. Index.html <form action="servlet1"> Name:<input type="text" name="userName"/><br/> <input type="submit" value="go"/> </form>
  • 67. FirstServlet.java try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("userName"); out.print("Welcome "+n); out.print("<form action='servlet2‘ method=‘post’>"); out.print("<input type='hidden' name='uname' value='"+n+"'>"); out.print("<input type='submit' value='go'>"); out.print("</form>"); out.close(); }catch(Exception e){System.out.println(e); } }
  • 68. SecondServlet.java try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("uname"); out.print("Hello "+n); out.close(); }catch(Exception e){ System.out.println(e); } }
  • 69. web.xml <web-app> <servlet> <servlet-name>s1</servlet-name> <servlet-class>FirstServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>/servlet1</url-pattern> </servlet-mapping> <servlet> <servlet-name>s2</servlet-name> <servlet-class>SecondServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s2</servlet-name> <url-pattern>/servlet2</url-pattern> </servlet-mapping> </web-app>
  • 70. URL Rewriting  In URL rewriting, we append a token or identifier to the URL of the next Servlet or the next resource.  We can send parameter name/value pairs using the following format: url?name1=value1&name2=value2&??  A name and a value is separated using an equal = sign,  A parameter name/value pair is separated from another parameter using the ampersand(&).  When the user clicks the hyperlink, the parameter name/value pairs will be passed to the server.  From a Servlet, we can use getParameter() method to obtain a parameter value.
  • 71. Advantage/Disadvantage of URL Rewriting Advantage It will always work whether cookie is disabled or not (browser independent). Extra form submission is not required on each pages. Disadvantage It will work only with links. It can send Only textual information.
  • 72. Index.html <form action="servlet1"> Name:<input type="text" name="userName"/><br/> <input type="submit" value="go"/> </form>
  • 73. FirstServlet.java try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("userName"); out.print("Welcome "+n); out.print("<a href='servlet2?uname="+n+"'>visit</a>"); out.close(); }catch(Exception e){System.out.println(e); } }
  • 74. SecondServlet.java try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("uname"); out.print("Hello "+n); out.close(); }catch(Exception e){ System.out.println(e); } }
  • 75. web.xml <web-app> <servlet> <servlet-name>s1</servlet-name> <servlet-class>FirstServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>/servlet1</url-pattern> </servlet-mapping> <servlet> <servlet-name>s2</servlet-name> <servlet-class>SecondServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s2</servlet-name> <url-pattern>/servlet2</url-pattern> </servlet-mapping> </web-app>
  • 76. HttpSession interface Container creates a session id for each user. The container uses this id to identify the particular user. An object of HttpSession can be used to perform two tasks: bind objects view and manipulate information about a session, such as the session identifier, creation time, and last accessed time.
  • 78. How to get the HttpSession object ? The HttpServletRequest interface provides two methods to get the object of HttpSession: public HttpSession getSession():Returns the current session associated with this request, or if the request does not have a session, creates one. public HttpSession getSession(boolean create):Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session.
  • 79. Methods of HttpSession interface  public String getId():Returns a string containing the unique identifier value.  public long getCreationTime():Returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT.  public long getLastAccessedTime():Returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT.  public void invalidate():Invalidates this session then unbinds any objects bound to it.
  • 80. Index.html <form action="servlet1"> Name:<input type="text" name="userName"/><br/> <input type="submit" value="go"/> </form>
  • 81. FirstServlet.java try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("userName"); out.print("Welcome "+n); HttpSession session=request.getSession(); session.setAttribute("uname",n); out.print("<a href='servlet2'>visit</a>"); out.close(); }catch(Exception e){System.out.println(e); } }
  • 82. SecondServlet.java try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); HttpSession session=request.getSession(false); String n=request.getParameter("uname"); out.print("Hello "+n); out.close(); }catch(Exception e){ System.out.println(e); } }
  • 83. web.xml <web-app> <servlet> <servlet-name>s1</servlet-name> <servlet-class>FirstServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>/servlet1</url-pattern> </servlet-mapping> <servlet> <servlet-name>s2</servlet-name> <servlet-class>SecondServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s2</servlet-name> <url-pattern>/servlet2</url-pattern> </servlet-mapping> </web-app>