0% found this document useful (0 votes)
16 views166 pages

Unit 1 Servlet

Uploaded by

sameersharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views166 pages

Unit 1 Servlet

Uploaded by

sameersharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 166

Servlets

TOPICS TO BE DISCUSSED
 WEB APPLICATION
 WAR FILE
 SERVERS
 PORTS
 SERVERSIDE PROGRAMMING
 WEB SERVER/APPLICATION SERVER
 CGI SCRIPT
 SERVLET
 CGI vs SERVLET
 SERVLET CONTAINER
 SERVLET PACKAGE
 SERVLET LIFE CYCLE
 FIRST SERVLET

2 26/10/2024
3 26/10/2024
War File

A war (web archive) File contains files of a web


project. It may have servlet, xml, jsp, image, html, css,
js etc. files.
What is war file?
web archive (war) file contains all the contents of a
web application. It reduces the time duration for
transferring file.

4 26/10/2024
Servers
 A server is a computer that responds to requests from a
client
 Typical requests: provide a web page, upload or download a file,
send email
 A server is also the software that responds to these
requests; a client could be the browser or other software
making these requests
 Typically, your little computer is the client, and someone
else’s big computer is the server
 However, any computer can be a server
 It is not unusual to have server software and client software running
on the same computer

26/10/2024
5
Apache
Apache is a very popular server
66% of the web sites on the Internet use
Apache
Apache is:
Full-featured and extensible
Efficient
Robust
Secure (at least, more secure than other
servers)
Up to date with current standards
Open source
Free

26/10/2024
6
Tomcat
 Tomcat is the Servlet Engine than handles
servlet requests for Apache
 Tomcat is a “helper application” for Apache
 It’s best to think of Tomcat as a “servlet container”
 Apache can handle many types of web services
 Apache can be installed without Tomcat
 Tomcat can be installed without Apache
 It’s easier to install Tomcat standalone than as
part of Apache
 By itself, Tomcat can handle web pages, servlets, and
JSP
 Apache and Tomcat are open source (and
therefore free)
26/10/2024
7
Ports
 A port is a connection between a server and a client
 Ports are identified by positive integers
 A port is a software notion, not a hardware notion, so there may be
very many of them
 A service is associated with a specific port
 Typical port numbers:
 21—FTP, File Transfer Protocol
 3306 —SQL SERVER
 25—SMTP, Simple Mail Transfer Protocol
 53—DNS, Domain Name Service
 80—HTTP, Hypertext Transfer Protocol
 8080—HTTP (used for testing HTTP)
These are the
ports of most
interest to us

26/10/2024
8
Why Server Side Programming?
 Though it is technically feasible to implement almost any business logic
using client side programs, logically or functionally it carries no ground when
it comes to enterprise applications (e.g. banking, air ticketing, e-shopping
etc.).
 To further explain, going by the client side programming logic; a
bank having 10,000 customers would mean that each customer should have a
copy of the program(s) in his or her PC which translates to 10,000 programs!
 In addition, there are issues like security, resource pooling, concurrent access
and manipulations to the database which simply cannot be handled by client
side programs. The answer to most of the issues cited above is ?
 Server Side Programming?.

9 26/10/2024
Server Side Programming

10 26/10/2024
Advantages of Server Side Programs
I. All programs reside in one machine called the
Server. Any number of remote machines (called
clients) can access the server programs.
II. New functionalities to existing programs can be
added at the server side which the clients? can
advantage without having to change anything
from their side.
III. Migrating to newer versions, architectures,
design patterns, adding patches, switching to
new databases can be done at the server side
without having to bother about clients
hardware or software capabilities.
11 26/10/2024
Advantages of Server Side
Programs Cont..
I. Issues relating to enterprise applications
like resource management, concurrency,
session management, security and
performance are managed by service side
applications.
II. They are portable and possess the
capability to generate dynamic and user-
based content (e.g. displaying transaction
information of credit card or debit card
depending on user?s choice).

12 26/10/2024
Advantages of Server Side
Programs Cont …
 The server-side extensions are nothing but the technologies that
are used to create dynamic Web pages. Actually, to provide the
facility of dynamic Web pages, Web pages need a container or
Web server. To meet this requirement, independent Web server
providers offer some proprietary solutions in the form
of APIs(Application Programming Interface).
 These APIs allow us to build programs that can run with a Web
server. In this case , Java Servlet is also one of the component
APIs of Java Platform Enterprise Edition which sets standards
for creating dynamic Web applications in Java

13 26/10/2024
Server: Web vs. Application

Server is a device or a computer program that


accepts and responds to the request made by other
program, known as client. It is used to manage the
network resources and for running the program or
software that provides services.
There are two types of servers:
Web Server
Application Server

14 26/10/2024
Web Server
 Web server contains only web or servlet container. It can be
used for servlet, jsp, struts, jsf etc. It can't be used for EJB.
 It is a computer where the web content can be stored. In
general web server can be used to host the web sites but
there also used some other web servers also such as FTP,
email, storage, gaming etc.
 Examples of Web Servers are:
 Apache Tomcat and Resin.

15 26/10/2024
Web Server
 A web server is the combination of computer and the
program installed on it. Web server interacts with the client
through a web browser. It delivers the web pages to the
client and to an application by using the web browser and
the HTTP protocols respectively.
 We can also define the web server as the package of large
number of programs installed on a computer connected to
Internet or intranet for downloading the requested files
using File Transfer Protocol, serving e-mail and building
and publishing web pages.

16 26/10/2024
Application Server

 Application server contains Web and EJB containers. It can


be used for servlet, jsp, struts, jsf, ejb etc. It is a component
based product that lies in the middle-tier of a server centric
architecture.
 It provides the middleware services for state maintenance
and security, along with persistence and data access. It is a
type of server designed to install, operate and host
associated services and applications for the IT services, end
users and organizations.

17 26/10/2024
The Example of Application Servers are:

JBoss: Open-source server from JBoss community.


Glassfish: Provided by Oracle.
Weblogic: Provided by Oracle. It more secured.
Websphere: Provided by IBM.

18 26/10/2024
CGI Scripts
CGI stands for “Common Gateway Interface”

Client sends a request to


server
Server starts a CGI script
client server
Script computes a result for
server and quits client
script
Server returns response
to client
Another client sends a
request
Server starts the CGI
script again
Etc.

26/10/2024
19
CGI Communication (traditional
approach)

Web browser
3. execute CGI program
and wait for CGI to terminate
5
1. request
CGI terminated

2 CGI profile file CGI Application


Web server (write result to CGI output file
4 CGI output file and terminate)

1. Web browser requset a response from CGI program.


2. Web server create CGI profile file that was contain information about CGI
variable, server and CGI output file.
3. Web server starts CGI application and wait for its termination.
4. CGI program runs and writes the result to CGI output file and then terminates.
5. Web server reads from CGI output file and send back to Web browser.
What is java servlet ?
A servlet is a small Java program that runs within a Web
server. Servlets receive and respond to requests from Web
clients, usually across HTTP, the HyperText Transfer
Protocol.

Request

Servlet

Client Response Server

21 26/10/2024
What is Servlet cont …

22 26/10/2024
Example use of Servlet

 Processing data POST over HTTPs using HTML form as purchase order or
credit card data
 Allowing collaborative between people such as on-line conferencing
 Many servlet can chain together among Web servers to reduce load on one
Web server.

23 26/10/2024
Why Use Servlets ?
One of the reasons that Java became
popular is Applets.
but there are problems with Applets
 Browser compatibility
 Download bandwidth

Server-side Java
the code is executed on the server side not
the client side
a dynamically loaded module that services
requests from a Web server

24 26/10/2024
Benefits

25 26/10/2024
Why Use Servlet

26 26/10/2024
Why use Servlet Cont …

27 26/10/2024
Servlets
A servlet is like an applet, but on the server side

Client sends a request to


server
Server starts a servlet
client server
Servlet computes a result
for server and does not client
quit servlet
Server returns response
to client
Another client sends a
request
Server calls the servlet
again
Etc.

26/10/2024
28
Servlet Communication

 Web browser request servlet by specified


URL as
Client Java-Enabled
http://www.host.com/serlet/servletName
HTML
Web Server  Web server call service() method in
Form
call ServletLoader class which will
Servlet
dynamically load a specified servlet
name from a special directory call
servlet.
Servlet
Servlets (contd.)
vs. Server-Side JavaScript
only available on certain web servers
vs. Active Server Pages (ASP)
only available on certain web servers

31 26/10/2024
32 26/10/2024
How Servlet Works

33 26/10/2024
Life Cycle of a Servlet
The web container maintains the life cycle
of a servlet instance. Let's see the life cycle
of the servlet:
1. Servlet class is loaded.
2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.

34 26/10/2024
Life cycle of Servlet

35 26/10/2024
Servlet Life Cycle
 The life cycle of the servlet is
controlled by the servlet container.
The servlet container is responsible
for doing following task
 When the first request is made for
servlet the containet loads the servlet
class and initiates it.
 Then make an instance of servlet
class.
 Initializes the servlet class by calling
init() method.
 Call the service method passes the
request response object to the service
method.
 If container need to remove the
servlet then call the destroy() method
to finalize the servlet.

36 26/10/2024
servlet

37 26/10/2024
Life Cycle of a Servlet (Servlet Life Cycle)
Cont ….

38 26/10/2024
39 26/10/2024
1) Servlet class is loaded

The classloader is responsible to load


the servlet class. The servlet class is
loaded when the first request for the
servlet is received by the web container.

40 26/10/2024
2) Servlet instance is created

The web container creates the instance


of a servlet after loading the servlet
class. The servlet instance is created
only once in the servlet life cycle.

41 26/10/2024
3) init method is invoked

The web container calls the init method


only once after creating the servlet
instance. The init method is used to
initialize the servlet. It is the life cycle
method of the javax.servlet.Servlet
interface.
 Syntax of the init method is given below:
public void init(ServletConfig config) thro
ws ServletException

42 26/10/2024
4) service method is invoked

 The web container calls the service method each time when
request for the servlet is received. If servlet is not initialized, it
follows the first three steps as described above then calls the
service method. If servlet is initialized, it calls the service
method. Notice that servlet is initialized only once.
 The syntax of the service method of the Servlet interface is given
below:
 public void service(ServletRequest request, ServletResponse res
ponse) throws ServletException, IOException

43 26/10/2024
5) destroy method is invoked

 The web container calls the destroy method before


removing the servlet instance from the service. It gives the
servlet an opportunity to clean up any resource for example
memory, thread etc.
 The syntax of the destroy method of the Servlet interface is
given below:
 public void destroy()

44 26/10/2024
Servlet Container

A servlet container is nothing but a


compiled, executable program.
The main function of the container is to
load, initialize and execute servlets

45 26/10/2024
46 26/10/2024
Servlet Container Cont ....

A Container have the capacity of containing many servlets


and can handle large number of requests. The Container
and the Objects of the container both are multi-threaded. It
can handle multiple requests concurrently.
All the servlets are managed by servlet container. It is
possible for the servlet container to run stand alone or
separately.

47 26/10/2024
Servlet Container

48 26/10/2024
Services provided by the Servlet
container :
 Network Services : Loads a Servlet class. The loading may be from a
local file system, a remote file system or other network services. The
Servlet container provides the network services over which the request
and response are sent.
 Decode and Encode MIME based messages : Provides the service of
decoding and encoding MIME-based messages.
 Manage Servlet container : Manages the lifecycle of a Servlet.
 Resource management : Manages the static and dynamic resource,
such as HTML files, Servlets and JSP pages.
 Security Service : Handles authorization and authentication of
resource access.
 Session Management : Maintains a session by appending a session
ID to the URL path

49 26/10/2024
The Container does the following thing-

 When the request comes at first for the servlet, then it load
the servlet, initialize it by calling servlet init() method.
 Makes a thread of the requested servlet
 Makes an instance of ServletRequest and ServletResponse
of javax.servlet.*; package
 Passes the ServletRequest and ServletResponse reference
variables to the servlet service method
 Take the ServletResponse object from the servlet and
passes to the web server
 And finally destroy the reference variables and destroy the
servlet when the is shut down.

50 26/10/2024
Servlet API ( Application Programming
Interface)

API ( Application Programming Interface ) is


a collection of classes and interfaces. There
are mainly two packages in servlet API

51 26/10/2024
Servlets API’s:
Servlets are build from two packages:
javax.servlet(Basic)
package contains many interfaces and classes that
are used by the servlet or web container. These are
not specific to any protocol.
javax.servlet.http(Advance)
 package contains interfaces and classes that are
responsible for http requests only.

52 26/10/2024
53 26/10/2024
PACKAGE SUMMARY
 java.io package povides the input and output
facilities, this package is a standard package of core
java platform. It is used for PrintWriter class
 javax.servlet :- ServletException class is contained
by this package. Every servlet throws the servlet
exception therefore it is necessary to include this
package in your program.
 javax.servlet.http :- HttpServletRequest and
HttpServletResponse interfaces are contained by
this package. The HttpServletRequest and
HttpServletResponse objects created by the servlet
container which is passes through the service
method doGet(), doPost(), etc. to get servlet request
and send servlet response to the client respectively.
54 26/10/2024
Http Servlet -
 HttpServlet is HTTP (Hyper Text Transfer Protocol )
specific servlet. It provides an abstract class
HttpServlet for the developers for extend to create
there own HTTP specific servlets.
 The sub class of HttpServlet must overwrite at least
one method given below-
 doGet()
 doPost()
 doTrace()
 doDelete()
 init()
 destroy()
 getServiceInfo()

55 26/10/2024
Difference B/W Generic and HTTP
servlet Package
Generic Servlet Http Servlet
 GenericServlet belongs  HttpServlet belongs to
to javax.servlet javax.servlet.http
package while package.
 GenericServlet is an  HTTPServlet is an
abstract class which
abstract class which
extends GenericServlet
extends Object and and implements
implements Servlet, java.io.Serializable.
ServletConfig and  HttpServlet must override
java.io.Serializable at least one method of
interfaces doGet(), doPost(),doPut(),
 . To write a doDelete(), init(),
GenericServlet you destroy(), getServletInfo().
 HTTPServlet is a protocol
need abstract service()
to be overridden dependent servlet.
 )GenericServlet is a

56
protocol-independent 26/10/2024
servlet
Javax.servlet package

57 26/10/2024
58 26/10/2024
javax.servlet.

This package provides many classes and


interfaces, which defines and describes the
difference between a servlet class and a
run time environment.
This package provides 14 interfaces and 9
classes.
They are-

59 26/10/2024
 Servlet - This interface defines method for all servlets interfac
 ServletConfig - This interface is used by servlet container to pass the
e
parameter to servlet. This interface is used for individual servlet and unknown
to the other servlets
 ServletContext - This interface contains a set of methods, which is used to
communicate with the servlet container and other servlets servlets within an
application
 ServletRequest - This interface provides a client request information to the
servlet
 ServletResponse - This interface provides a servlet response information to
the client, it assists the servlet to send the response information to the client.
 RequestDispatcher - This interface accepts the request from the client sends
it to the other application resources.
 Filter - It performs the filter task on either request or response to the resources

60 26/10/2024
Interface cont
…. for a resource.
 FilterChain - This view a chain of filter request
 FilterConfig - It used by the servlet container to pass the information
during initialization to the of the filter
 ServletContextListener - This interface receive a notification when a
ServletContext of a web application is initialaised
 ServletRequestListener - This interface can be implemented if
developer wants to notify when any request out of the scope of web
application is coming
 ServletContextAttributeListener - This interface receive a notification
when a change is made in the ServletContext
 ServletRequestAttributeListener - This interface receive a notification
when changes is made in request attribute.
 SingleThreadModel - This interface is deprecated after the java servlet
2.4.

61 26/10/2024
Classes
 GenericServlet - This class defines a generic, protocol independent servlet.
 ServletContextAttributeEvent - This is a event class for, when the attribute of
an application changes this class receives a nification.
 ServletContextEvent - This class receive a notifications when the
ServletContext of an application is changes.
 ServletInputStream - This provides a servlet input stream for reading binary
data from the client.
 ServletOutputStream - This class provides an output steam for sending binary
data to the client.
 ServletRequestWrapper - This class provides the implementation of
ServletRequest interface, the developers can subclass this for their own specific
use
 ServletResponseWrapper - This class provides the implementation of
ServletResponse interface, the developers can subclass this for their own specific
use
 ServletRequestAttributeEvent - This is a event class it receive a notification
when any change made in the request attribute of the application
 ServletRequestEvent - This event class indicates the events of the servlet class
62 26/10/2024
javax.servlet.http.

This package provides classes and interfaces which is


HTTP protocol specific.
There are 8 interfaces and 7 classes in this package

63 26/10/2024
Interfaces
 HttpServletRequest - This interface extends the ServletRequest interface
for provide http specific servlet request
 HttpServletResponse - This interface extends the ServletResponse interface
for provide http specific servlet response
 HttpSession - It provides a way for identifying a user on the website
 HttpSessionActivationListener - This interface notify when when session is
Activated
 HttpSessionAttributeListener - This interface can be implemented in order
to get notification when attribute of the session is changed
 HttpSessionBindingListener - This interface can be implemented in order
to get notification when object is bound or unbound to the session
 HttpSessionContext - This interface is deprecated in servlet 2.1 for security
resion
 HttpSessionListener - When developer want to notify the session activation
or de-activation, can implement this interface

64 26/10/2024
Classes
 Cookie - It creates a cookie sent by a servlet to the web browser, which
browser saves and latter return for further communication
 HttpServlet - This is an abstract class, to create a Http specific servlet
you need to extend this class
 HttpServletRequestWrapper -This class implements the
HttpServletRequest interface, the developer can also subclass this for
their specific use
 HttpServletResponseWrapper - This class implements the
HttpServletResponse interface, the developer can also subclass this for
their specific use
 HttpSessionBindingEvent - This is an events class, it is activated
when session is bound and unbound
 HttpSessionEvent - This event class generates a notification for
changes to the session within a web application
 HttpUtils - This class is deprecated in servlet 2.3 API

65 26/10/2024
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.

66 26/10/2024
Methods of Servlet interface
There are 5 methods in Servlet interface. The init,
service and destroy are the life cycle methods of
servlet. These are invoked by the web container.

67 26/10/2024
ServletRequest Interface

An object of ServletRequest is used to


provide the client request information to a
servlet such as content type, content
length, parameter names and values,
header informations, attributes etc

68 26/10/2024
69 26/10/2024
Index.html

<body>
<form action ="first">
 <p> Name<input type="text"
name="username"></p>
 <p> <input type="submit"
value="first"></p>
 </form>
</body>

70 26/10/2024
SERVLET CODE
 out.println("<h1>Welcome to my first
servlet</h1>");
String user =
request.getParameter("username");
 out.println("<h2> Welcome
"+user+"</h2>");
 java.util.Date date = new java.util.Date();
 out.println("<h2>"+"Current Date &
Time: " +date.toString()+"</h2>");

71 26/10/2024
QUESTION:
DISPLAY DATAE AND TIME IN THIS FORMAT
Display Current Date & Time
Mon 2010.06.21 at 10:06:44 PM
GMT+04:00

72 26/10/2024
Html code
<form action="Counter">
 <h1> <input type="submit"
value="submit"></h1>
 </form>

73 26/10/2024
HIT COUNTER
Servlet interface
import java.io.*; provides common behavior to all
import javax.servlet.*; the servlets.Servlet interface
import javax.servlet.http.*; defines methods that all servlets
must implement.
public class Counter extends HttpServlet{
int counter = 0;

public void doGet(HttpServletRequest request, HttpServletResponse


response)throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter pw = response.getWriter();
counter++;
pw.println(“TOTAL COUNT= " + counter);
}
}

74 26/10/2024
RequestDispatcher in Servlet

The RequestDispatcher interface provides the facility


of dispatching the request to another resource it may
be html, servlet or jsp.
This interface can also be used to include the content
of another resource also. It is one of the way of servlet
collaboration.
There are two methods defined in the
RequestDispatcher interface.

75 26/10/2024
Methods of RequestDispatcher
interface
 The RequestDispatcher interface provides two methods. They are:
 public void forward(ServletRequest request,ServletResponse
response)throws ServletException,java.io.IOException:
 Forwards a request from a servlet to another resource (servlet, JSP
file, or HTML file) on the server.
 public void include(ServletRequest request,ServletResponse
response)throws ServletException,java.io.IOException:Includes
 the content of a resource (servlet, JSP page, or HTML file) in the
response.

76 26/10/2024
IN GIVEN figure, response of second servlet is
sent to the client. Response of the first servlet is
not displayed to the user.

77 26/10/2024
IN GIVEN figure, response of second servlet is included in
the response of the first servlet that is being sent to the
client.

78 26/10/2024
Html code
<body>
<form action="Login" method="post">
Name:<input type="text"
name="userName"/><br/>
Password:<input type="password"
name="userPass"/><br/>
<input type="submit" value="login"/>
</form>
</body>

79 26/10/2024
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Login extends HttpServlet {
Login.java
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

String username=request.getParameter("userName");
String paas=request.getParameter("userPass");

if(paas.equals("sharma"))
{
RequestDispatcher rd=request.getRequestDispatcher("welcomeservlet");
rd.forward(request, response);
}
else{
out.print("Sorry UserName or Password Error!");
RequestDispatcher rd=request.getRequestDispatcher("/index.html");
rd.include(request, response);
80 26/10/2024
} } }
welcomeservlet
out.println("<h1>welcome to servlet
</h1>");

//String user =
request.getParameter("username");
 // out.println("<h2> Welcome
"+user+"</h2>");

81 26/10/2024
SendRedirect in servlet

The sendRedirect() method


of HttpServletResponse interface can be
used to redirect response to another
resource, it may be servlet, jsp or html file.
It accepts relative as well as absolute URL.
It works at client side because it uses the
url bar of the browser to make another
request. So, it can work inside and outside
the serve

82 26/10/2024
HTML CODE
<form action=" SendServlet ">
 <h1> <input type="submit"
value="submit"></h1>
 </form>

83 26/10/2024
sendRedirect()
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SendServlet extends HttpServlet{


public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();

response.sendRedirect("https://www.amazon.in/");

pw.close();
}}

84 26/10/2024
HTML CODE
<form action=“GoogleSearch">
<input type="text" name="name">
<input type="submit" value="Google Sear
ch">
</form>

85 26/10/2024
sendRedirect()
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class GoogleSearch extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpSe
rvletResponse response)
throws ServletException, IOException {

String name=request.getParameter("name");
response.sendRedirect("https://www.google.co.in/
#q="+name);
}
}
86 26/10/2024
FORWARD() SENDREDIRECT()

The forward() method is executed The sendRedirect() method is


in the server side. executed in the client side.
The request is transfer to other The request is transfer to other
resource within same server. resource to different server.

It does not depend on the client’s


The sendRedirect() method is
request protocol since the forward
provided under HTTP so it can be
( ) method is provided by the
used only with HTTP clients.
servlet container.

The request is shared by the target New request is created for the
resource. destination resource.
Only one call is consumed in this Two request and response calls are
method. consumed.
It is declared in It is declared in
RequestDispatcher interface. HttpServletResponse.

87 26/10/2024
FORWARD() SENDREDIRECT()

The sendRedirect() method is


The forward() method is
slower because when new
faster than sendRedirect()
request is created old request
method.
object is lost.

It can be used within and


It can be used within server.
outside the server.

Signature :
forward(ServletRequest Signature:
request, ServletResponse void sendRedirect(String url)
response)

88 26/10/2024
Some more points to notice of forward vs
sendRedirect.

Session is not lost in both cases.


The above differences are applicable to Servlets
and JSPs. In Servlets, these methods are used in
service() and in JSP used in scriptlets.
In frameworks like Struts, the Controller can
decide, at the end of request processing, which
one to use of either forward or redirect operation.
The Controller also can decide with forward()
method, to what resource the forward should be
made, depending on different conditions of client
request requirements.

89 26/10/2024
Which one is preferred?

Just depends on the scenario.


If you would like to forward the client request
to a new resource on the same server for
further process, prefer forward() where data of
the original resource can be passed to the new
resource.
If you would like to transfer the control to a
new server or domain where client treats as a
new task, prefer sendRedirect(). If the data of
the original resource (which client requested)
is needed in the new resource, store them in
Session object and reuse.
90 26/10/2024
HTML FILE FOR Multiple values for a single parameter

<form action="GetParameterValues" method="post">

BAALUSHAH <input type="checkbox" name="Sweetdish"


value="BAALUSHAHI" > </input>

BARFI <input type="checkbox" name="Sweetdish"


value="BARFI" /> </input>

<input type="checkbox" name="Sweetdish" value="RASGULLA"


/>RASGULLA </input>
<input type="submit">

</form>
91 26/10/2024
Reading Parameter values
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class GetParameterValues extends HttpServlet{

protected void doPost(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String[] Sweetdish = request.getParameterValues("Sweetdish");
for(int i=0; i< Sweetdish.length; i++){
pw.println("<br> Sweetdish : " + Sweetdish[i]);
} }}

92 26/10/2024
Servlet types
There are mainly two types of servlets -
Generic Servlet - Generic
servlet is protocol
independent servlet. It
implements the Servlet and
ServletConfig interface. It
may be directly extended by
the servlet. Writing a servlet
in in GenericServlet is very
easy. It has only init() and
destroy() method of
ServletConfig interface in its
life cycle. It also implements
the log method of
ServletContext interfac

93 26/10/2024
ServletConfig Interface

An object of ServletConfig is created by the


web container for each servlet. This object
can be used to get configuration
information from web.xml file.
If the configuration information is modified
from the web.xml file, we don't need to
change the servlet. So it is easier to
manage the web application if any specific
content is modified from time to time.

94 26/10/2024
Advantage of ServletConfig

The core advantage of ServletConfig is that


you don't need to edit the servlet file if
information is modified from the web.xml
file.

95 26/10/2024
How to get the object of ServletConfig

getServletConfig() method of Servlet


interface returns the object of
ServletConfig.
Syntax of getServletConfig() method
public ServletConfig getServletConfig();

96 26/10/2024
ServletContext Interface in Servlet

For every Web


application a ServletContext object is
created by the web container.
ServletContext object is used to get
configuration information
from Deployment Descriptor(web.xml)
which will be available to any servlet or
JSPs that are part of the web app.

97 26/10/2024
Commonly used methods of ServletContext
interface

98 26/10/2024
How to get the object of ServletContext
interface

getServletContext() method of
ServletConfig interface returns the object of
ServletContext.
getServletContext() method of
GenericServlet class returns the object of
ServletContext.
Syntax of getServletContext() method
public ServletContext getServletContext()

99 26/10/2024
Advantages of ServletContext

Provides communication between servlets


Available to all servlets and JSPs that are
part of the web app
Used to get configuration information from
web.xml

10 26/10/2024
0
10 26/10/2024
1
HTML FILE
<form action="MyServlet">
<input type="submit"
value="submit">
</form>

10 26/10/2024
2
SERVLET FILE
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class MyServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");

PrintWriter out = response.getWriter();


ServletContext sc = getServletContext();

out.println(sc.getInitParameter("dname"));

}}

10 26/10/2024
3
Web.xml
<context-param>
<param-name>dname</param-name>
<param-
value>sun.jdbc.odbc.JdbcOdbcDriver</
param-value>
</context-param>

10 26/10/2024
4
ServletConfig

ServletConfig available in javax.servlet.*; package


ServletConfig object is one per servlet class
Object of ServletConfig will be created during initialization process of
the servlet
This Config object is public to a particular servlet only
Scope: As long as a servlet is executing, ServletConfig object will be
available, it will be destroyed once the servlet execution is completed.
We should give request explicitly, in order to create ServletConfig object
for the first time
In web.xml – <init-param> tag will be appear under <servlet-class> tag

10 26/10/2024
5
ServletContext
ServletContext available in javax.servlet.*; package
ServletContext object is global to entire web application
Object of ServletContext will be created at the time of web
application deployment
Scope: As long as web application is executing, ServletContext object will be
available, and it will be destroyed once the application is removed from the
server.
ServletContext object will be available even before giving the first request
In web.xml – <context-param> tag will be appear under <web-app> tag
So finally…….
No. of web applications = That many number of ServletContext objects [ 1 per
web application ]
No. of servlet classes = That many number of ServletConfig objects

10 26/10/2024
6
Difference between ServletConfig and
ServletContext

The servletconfig object refers to the single


servlet whereas servletcontext object refers
to the whole web application.

10 26/10/2024
7
Attribute in Servlet

An attribute is an object that is used to


share information in a web app. Attribute
allows Servlets to share information among
themselves.
Attributes can be SET and GET t or
removed from one of the following scopes

10 26/10/2024
8
Attribute in Servlet

1.Request: The request attribute can be accessible


within that same servlet Request.
2.Session: these attributes are accessible within the
same Http Session.
3.Context /Application: any servlet within the same
application can have access to context attributes.
The servlet programmer can pass information from
one servlet to another using attributes. It is just like
passing object from one class to another so that we can
reuse the same object again and again.

10 26/10/2024
9
What we do with these attributes?

setAttribute (): This method is used to set the attribute


values into objects.
getAttribute (): This method is used to get the attribute
values from scope objects.
getAttributeNames (): This method is used to get the
name of Attribute objects.
removeAttribute (): this method is used to remove
attributes from the respective scopes of objects.

11 26/10/2024
0
Attribute specific methods of ServletRequest,
HttpSession and ServletContext interface

public void setAttribute(String name,Object


object):sets the given object in the application scope.
public Object getAttribute(String name):Returns the
attribute for the specified name.
public Enumeration getInitParameterNames():Returns
the names of the context's initialization parameters as
an Enumeration of String objects.
public void removeAttribute(String name):Removes
the attribute with the given name from the servlet
context.

11 26/10/2024
1
HTML FILE
<form action="First">
<input type="submit"
value="submit">
</form>

11 26/10/2024
2
First.java to SET an Attribute

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class First extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();

ServletContext sc = getServletContext();
sc.setAttribute("user","MCA"); //setting attribute on context scope

out.println("<a href='Second'>visit</a>");
}
}

11 26/10/2024
3
Second.java to GET An Attribute

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Second extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
ServletContext sc = getServletContext();

String str = (String) sc.getAttribute("user"); //getting attribute from context scope

out.println("Welcome"+str); // Prints : Welcome MCA


}
}

11 26/10/2024
4
How servlet is used with each scope
of Object?
 1.Request Attribute:
 “This object attributes are accessible only within that same servlet request
object.”
 We can set and get Request Attributes with an object.
You can do all the operations mentioned above with request object.
For example:
 Request.setAttribute(“fruits”,FruitsObject);
 Request.getAttribute(“fruits”)

11 26/10/2024
5
Session Tracking in Servlet

Session is the conversion of user within span of time.


In general meaning particular interval of time.
Tracking is the recording of the thing under session.
Session Tracking is remembering and recording of
client conversion in span of time. It is also called as
session management.
If web application is capable of remembering and
recording of client conversion in span of time then that
web application is called as stateful web application.

11 26/10/2024
6
Why need Session Tracking ?
 Http protocol is stateless, to make stateful
between client and server we need Session
Tracking.
 Session Tracking is useful for online shopping,
mailing application, E-Commerce application to
track the conversion.
 Http protocol is stateless, that means each
request is considered as the new request. You
can see in below image

11 26/10/2024
7
Why use Session Tracking ?
To recognize the user It is used to recognize
the particular user.
Why Http is design as stateless
protocol ?
If Http is stateful protocol for multiple
requests given by client to web application
single connection will be used between
browser and web server across the multiple
requests. This may make clients to engage
connection with web server for long time
event though the connection are ideal. Due
to this the web server reach to maximum
11
connections even though most of its 26/10/2024
8
connection are idle. To overcome this
Session tracking methods:

User authorization
Hidden fields
URL rewriting
Cookies
Session tracking API

11 26/10/2024
9
SESSION TRACKING TECHNIQUES

BUILD ON THE TOP OF ALL ABOVE 4 APIS’ SESSION API

12 26/10/2024
0
Multiple CheckBox Example

 import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class CheckBox extends HttpServlet{
public void doGet(HttpServletRequest req, HttpServletResponse res)throws ServletException,
IOException{
String name;
String[] hobbies;
res.setContentType("text/html");
name= req.getParameter("name");
PrintWriter pw = res.getWriter();
hobbies= req.getParameterValues("hobbies");
if(hobbies!=null)
{
pw.println("<html><body bgcolor=#00fffff>");
pw.println("Hi I am <h4>"+name+".</h4><br>");
pw.println("My hobby/hobbies are:");
for(int i=0; i<hobbies.length; i++){
pw.println(hobbies[i]+",");
}
pw.println("</body></html>");
}
else
pw.println("<p><font color=red>not selected</font></p>");
}
12 } 26/10/2024
1
Deployment Descriptors

A web application's deployment descriptor


describes the classes, resources and
configuration of the application and how the
web server uses them to serve web requests.
When the web server receives a request for the
application, it uses the deployment descriptor
to map the URL of the request to the code that
ought to handle the request.
The deployment descriptor is a file
named web.xml. It resides in the app's WAR
under the WEB-INF/ directory. The file is an XML
file whose root element is <web-app>.
12 26/10/2024
2
Cookie

12 26/10/2024
3
cookie
Cookies are text files stored on the client computer and
they are kept for various information like name, a single
value, and optional attributes such as a comment, path
and domain qualifiers, a maximum age, and a version
number.
• or
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.
12 26/10/2024
4
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.

12 26/10/2024
5
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

12 26/10/2024
6
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 use

12 26/10/2024
7
When use cookies ?

When session ID is not required and when


less number of input values are submitted
by client in that case in place of using
HttpSession Technique you can use cookies
Technique to reduce the burden on server.

12 26/10/2024
8
Points to Remember

Cookies is pressistance resource which is


stores at client location.
We can store 3000 cookies in cookies file at
a time.
The cookies are introduced by net scape
communication.
Cookies files exist up to 3 year.
Size of cookies is 4 kb.

12 26/10/2024
9
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.

13 26/10/2024
0
Advantage of Cookies
Simplest technique of maintaining the
state.
Cookie are maintained at client side so they
do not give any burden to server.
All server side technology and all web
server, application servers support cookies.
Presistent cookies can remember client
data during session and after session with
expiry time.

13 26/10/2024
1
Limitation of Cookies

 It will not work if cookie is disabled from


the browser.
Cookies are text files, It does not provides
security. Any one can change this file.
With coockies need client support that
means if client disable the coockies then it
does not store the client location.
Cookies can not store java objects as
values, they only store text or string.

13 26/10/2024
2
Session Cookies

request request

put cookie id1 Servlet


Servlet
id1
response response
id1
Web
browser 1 Create Session
Web server

13 26/10/2024
3
Session Cookies

request request

put cookie id2 id2


Servlet
Servlet
id2
response response
id1
Web
browser 2 Create Session
Web server

13 26/10/2024
4
Session Cookies

request request
Cookie: id1
id2
Servlet
Servlet
id1
response response
id1
Web
browser 1 Session
Web server read/write

13 26/10/2024
5
Session Cookies

request request
Cookie: id2
id2
Servlet
Servlet
id2
response response
id1
Web
browser 2 Session
Web server read/write

13 26/10/2024
6
Create Cookies

To create cookies you need to use Cookie


class of javax.servlet.http package.
Syntax
Cookie c=new Cookie(name, value);
// here name and value are string type

13 26/10/2024
7
Add Cookies

To add a cookie to the response object, we


use
 addCookie() mehtod.
Syntax
Cookie c=new Cookie(); //creating cookie
object response.addCookie(c1); //adding
cookie in the response

13 26/10/2024
8
Read Cookies for browser

To read Cookies from browser to a servlet,


we need to call getCookies methods given
by request object and it returns an array
type of cookie class.
Syntax
response.addCookie(c1);
Cookie c[]=request.getCookie();

13 26/10/2024
9
HTML CODE
 <form action="FirstServlet"
method="post">
Name:<input type="text"
name="userName"/> <br/>
<input type="submit" value="continue"/>
</form>

14 26/10/2024
0
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response) throws


ServletException , IOException {
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='SecondServlet' method='post'>");


out.print("<input type='submit' value='continue'>");
out.print("</form>");

14
out.close(); 26/10/2024
1 } }
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {

public void doPost(HttpServletRequest request,


HttpServletResponse response)throws ServletException ,
IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());
out.close();
14 } } 26/10/2024
2
URL rewriting:

URL rewriting is a way of appending data at


the end of URL. Data is appended in name
value pair form. Multiple parameters can be
appended in one URL with name value
pairs.

14 26/10/2024
3
How to get parameter value from url
in servlet?

HttpServletRequest interface’s getParameter() method


is used to get parameter value from url in servlet.
Syntax:
String value = request.getParameter(“fieldName”);

14 26/10/2024
4
Advantages of URL rewriting:

As data is appended in the URL it is easy to


debug.
It is browser independent.
Limitations of URL rewriting:
Not secure because data is appended in
the URL.
Can’t append large no. of parameters
because URL length is limited.

14 26/10/2024
5
14 26/10/2024
6
HTML CODE
<form action="Servlet1">
Name <input type="text"
name="uname">
<input type="submit"
value="submit">
</form>

14 26/10/2024
7
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Servlet1 extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) ) throws


ServletException , IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

String n=request.getParameter("uname");
out.print("Welcome "+n);

//appending the username in the query string


out.print("<a href='servlet2?uname="+n+"'>visit</a>");

out.close();
}
}

14 26/10/2024
8
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Servlet2 extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) ) throws


ServletException , IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

//getting value from the query string


String n=request.getParameter("uname");
out.print("Hello "+n);

out.close();
}
}

14 26/10/2024
9
Hidden Form Field

Tracking client conversion using Html


hidden variables in secure manner is known
as hidden form field.
How to use Hidden Form Field ?
Syntax of Hidden field is:
<input type="hidden"> and with this
we assign session ID value.
Syntax
<input type="hidden" name=“sname"
value=“mca">

15 26/10/2024
0
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.
Real application of hidden form field
It is widely used in comment form of a
website. In such case, we store page id or
15
page name in the hidden field so that 26/10/2024
each
1
page can be uniquely identified.
15 26/10/2024
2
15 26/10/2024
3
Hidden Form Field Advantage

Basic knowledge of html is enough to work


with this technique.
It will always work whether cookie is
disabled or not.
Hidden boxes resides in web pages of
browser window so they do not provide
burden to the server.
This technique can be used along with all
kind of web server or application server.

15 26/10/2024
4
Hidden Form Field Limitations
More complex than URL Rewriting.
It is maintained at server side.
Extra form submission is required on each
pages.
Hidden form field can not store java object
as values. They only store text value
It Also increase network traffic because
hidden boxes data travels over the network
along with request and response.
Hidden boxes does not provides data
security because their data can be view
15
5
through view source option. 26/10/2024
HTML FILE
<form action="FirstServlet ">
 Name:<input type="text"
name="userName"/>
 <br/>
<input type="submit" value="continue"/>
 </form>

15 26/10/2024
6
mport java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response){

response.setContentType("text/html");
PrintWriter out = response.getWriter();

String n=request.getParameter("userName");
out.print("Welcome "+n);
out.print("<form action='servlet2' >");
out.print("<input type='hidden' name='uname' value='"+n+"'>");
out.print("<input type='submit' value='continue'>");
out.print("</form>");
out.close();
}
15 26/10/2024
7 }
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();

//Getting the value from the hidden field


String n=request.getParameter("uname");
out.print("Hello "+n);

out.close();
}catch(Exception e){System.out.println(e);}
}
}
15 26/10/2024
8
HttpSession interface

In such case, 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:
I. bind objects
II. view and manipulate information about a
session, such as the session identifier,
creation time, and last accessed time.

15 26/10/2024
9
16 26/10/2024
0
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,
16 26/10/2024
1 returns a new session.
 Commonly used 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.

16 26/10/2024
2
< form action="login">
 User Name:<input type="text"
name="userName"/> <br/>
 Password:<input
type="password"name="userPassword"/>
<br/> <input type="submit"
value="submit"/> </form>

16 26/10/2024
3
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet1 extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter pwriter = response.getWriter();

16 26/10/2024
4
String name = request.getParameter("userName");
String password = request.getParameter("userPassword");
pwriter.print("Hello "+name);
pwriter.print("Your Password is: "+password);
HttpSession session=request.getSession();
session.setAttribute("uname",name);
session.setAttribute("upass",password);
pwriter.print("<a href='welcome'>view details</a>");
pwriter.close();
}catch(Exception exp){
System.out.println(exp);
}
16 } 26/10/2024
5
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter pwriter = response.getWriter();
HttpSession session=request.getSession(false);
String myName=(String)session.getAttribute("uname");
String myPass=(String)session.getAttribute("upass");
pwriter.print("Name: "+myName+" Pass: "+myPass);
pwriter.close();
}catch(Exception exp){ System.out.println(exp);
}
16 26/10/2024
6 }

You might also like