0% found this document useful (0 votes)
22 views32 pages

Dynamic Web Paging Using: Java Servlet

Java sem 5 material

Uploaded by

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

Dynamic Web Paging Using: Java Servlet

Java sem 5 material

Uploaded by

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

Dynamic Web Paging using

Java Servlet

Prepared By : Shivani Trivedi.


What is Servlet?
• Server + Applet
• Server Side Java Programming which runs at
Browser and used to create dynamic
webpages.
• Servlet is a dynamically loaded module that
services requests from a Web server.
Servlet technology is used to create web
application (resides at server side and
generates dynamic web page).
• Servlet is an API that provides many
interfaces and classes.

Request
Web Web
Browser Server Servlet

Response
Why Servlet?
• Before Servlet there was a CGI (common gateway interface)
to create a
dynamic webpages with all languages like c++, java etc.
• Working Method of CGI:
– When Client makes a URL Request for dynamic web
page to CGI, CGI will create a individual Process for
each and every request which is not implemented on
Server.
• Drawbacks of CGI:
– Low Performance
– Server is not utilized
– Native Interface: so, Not Portable
• So, Java Servlet is released by Sun Microsystems.
Advantages of Servlet
• Efficiency
o More efficient – uses lightweight java threads as
opposed to individual processes
• Persistency
o Servlets remain in memory
o Servlets can maintain state between requests
• Portability
o Since servlets are written in Java, they are platform
independent
• Robustness
o Error handling, Garbage collector to prevent problems
with memory leaks
o Large class library – network, file, database, distributed
object components, security, etc.
Advantages….
• Extensibility
– Creating new subclasses that suite your needs
• Inheritance, polymorphism, etc.
• Security
– Security provided by the server as well as the Java Security
Manager
• Powerful
– Servlets can directly talk to web server
– Facilitates database connection pooling, session tracking
etc.
• Convenient
– Parsing and decoding HTML form data, reading and setting
HTTP headers, handling cookies, etc.
Java Servlet Architecture
• Java Servlet Architecture provided by Servlet
API.
• Following are two packages provides
Architecture to the Servlet.
– javax.servlet
• Contains generic interfaces and classes that are
implemented and extended by all servlets
– javax.servlet.http
• Contains classes that are extended when creating HTTP-
specific servlets
Servlet Implementation
• Implementation of servlet can be done using
following 4 ways:
– Servlet Interface
– GenericServlet Class
– HttpServlet Class
– Single Thread Model
Servlet Interface
• Servlet Interface provides life cycle to the servlet.
• So we have to compulsory implement this interface
into the our servlet class.
• Servlet interface has following methods:
1. Public void init (ServletConfig config) throws
ServletException
2. Public void service(ServletRequest req, ServletResponse
res) throws ServletException, IOException
3. Public void destroy()
4. Public ServletConfig getServletConfig()
5. Public String getServletInfo()
GenericServlet Class
• When we implemented servlet interface we
must to override all methods of that interface
into our servlet class
• So for that an Abstract GenericServlet class is
created.
• In that three interfaces are implemented:
– Servlet Interface  javax.servlet
– ServletConfig Interface  javax.servlet
– Serializable Interface  java.io
GenericServlet…
<<Interface>>
<<Interface>> javax.servlet.ServletConfig
javax.servlet.Servlet <<Interface>>
javax.io.Serializable getInitParameter( )
init( ) getServletContext( )
getServletConfig( ) getInitParameterNames( )
service( ) getServletName( )
getServletInfo( )
destroy( )
Implemented

javax.servlet.GenericServlet
init( )
getServletConfig( )
service( )
getServletInfo( )
destroy( )
getInitParameter( )
getServletContext( )
getInitParameterNames( )
getServletName( )
log( )

Extends
New Servlet
Simple Servlet Program
import java.io.*;
import javax.servlet.*;
public class SimpleServlet extends GenericServlet
{
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<B><I> Example of Generic Servlet Class");
out.close();
}
}
Servlet Life Cycle
If servlet is already loaded
Servicing requests by
calling the
service method
Calling the
init method
Destroying the servlet
ServletConfig by calling the
Initialization destroy method
and Loading

Garbage
Servlet Class Collection
Servlet Life Cycle….
Life Cycle of Servlet describes followings three methods
init()
 public void init(ServletConfig config) throws
ServletException
service()
 public void service(ServletRequest req, ServletResponse
res) throws ServletException, IOException
destroy()
 public void destroy()
These methods are provided by Servlet Interface of javax.servlet
package.
• The init() method is called only once by the servlet
container throughout the life of a servlet.
• Parameters - The init() method takes a
ServletConfig object that contains the initialization
parameters and servlet's configuration and throws
a ServletException if an exception has occurred.
• Once the servlet starts getting the requests, the
service() method is called by the servlet container
to respond.
• Parameters - The service() method takes the
ServletRequest object that contains the client's
request and the object ServletResponse contains
the servlet's response.
• The service() method throws ServletException and
IOExceptions exception.
• destroy() method is called when we need to close
the servlet.
• That is before removing a servlet instance from
service, the servlet container calls the destroy()
method.
• Once the servlet container calls the destroy()
method, no service methods will be then called .
• That is after the exit of all the threads running in
the servlet, the destroy() method is called.
• Hence, the servlet gets a chance to clean up all the
resources like memory, threads etc which are
being held.
Life cycle of servlet
import java.io.*;
import javax.servlet.*;
public class ServletLifeCycle extends GenericServlet
{
int count;
public void init(ServletConfig config) throws ServletException
{
count =1;
}
public void service(ServletRequest req,ServletResponse res) throws
ServletException,IOException
{
res.setContentType("text/plain");
PrintWriter out=res.getWriter();
out.println("Value of count is :"+count++);
}
public void destroy()
{
System.out.println("Destroyed");
}
}
HttpServlet Class
• HttpServlet class is a member of
javax.servlet.http package
• Basic differences between GenericServlet class
and HttpServlet Class are:
– GeneriServlet class provides protocol independent
Servlet transaction. Whereas HttpServlet class
provides protocol depended (HTTP) servlet
transcation.
– GenericServlet can not handle http request and
response
– So, GenericServlet can not provide handle session
tracking approaches like cookie and session.
HttpServlet… <<Interface>>
<<Interface>> javax.servlet.ServletConfig
javax.servlet.Servlet <<Interface>>
javax.io.Serializable getInitParameter( )
init( ) getServletContext( )
getServletConfig( ) getInitParameterNames( )
service( ) getServletName( )
getServletInfo( ) Implements
destroy( )
javax.servlet.GenericServlet
init( )
getServletConfig( )
service( )
getServletInfo( )
destroy( )
getInitParameter( )
getServletContext( )
getInitParameterNames( )
getServletName( )
log( )
Extends
javax.servlet.http.HttpServlet
doDelete( )
doGet( )
doOptions( )
doPost( )
doPut( )
doTrace( )
getLastModified( )
service( )
Extends
New Servlet
HttpServlet Class
• Http request can be done using two ways:
– Get Method
– Post Method

Web HttpServlet subclass


GET request Server
doGet()
response
service()
POST request
doPost()
response
Methods of HttpServlet Class
• doPost:
– Data sent in two steps
– Designed for Posting information
 Browser contacts server
 Sends data
– doPost( ) method is called by the server via the service( ) method to
handle an HTTP POST request
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, java.io.IOException
• doGet:
– Contacts server and sends data in single step
– Appends data to action URL separated by question mark
– Designed to get information
– doGet( ) is called by the server via the service( ) method to handle
an HTTP GET request.
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, java.io.IOException
Methods….
• PUT: Place documents directly on server via FTP
• DELETE: Opposite of PUT
• TRACE: Debugging aid returns to client contents of its
request
• OPTIONS: what options available on server. which HTTP
methods the server supports and sends the information
back to the client by way of a header.
Example
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet
{
public void doGet(HttpServletRequest req,
HttpServletResponse res) throws ServletException,
IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<HTML><HEAD><TITLE>Hello
World</TITLE></HEAD>");
out.println("<BODY><B><Center>Hello World
</BODY></HTML>");
out.close();
}
}
SingleThreadModel
• Normally, the system makes a single instance of
your servlet and then creates a new thread for
each user request.
• This means that if a new request comes in while
a previous request is still executing, multiple
threads can concurrently be accessing the same
servlet object.
• Consequently, your doGet and doPost methods
must be careful to synchronize access to fields
and other shared data (if any) since multiple
threads may access the data simultaneously.
• you can prevent multithreaded access by having
your servlet implement the SingleThreadModel
interface, as below.
• public class YourServlet extends HttpServlet
implements SingleThreadModel
• { ... }
• If you implement this interface, the system
guarantees that there is never more than one
request thread accessing a single instance of your
servlet.
• SingleThreadModel interface is deprecated in the
servlet 2.4 (JSP 2.0) specification.
• You are much better off using explicit synchronized
blocks.
RMI (Remote Method Invocation)
The RMI (Remote Method Invocation) is an API that provides a mechanism to create
distributed application in java.
RMI was introduced by Sun Microsystems as an alternative to the complex coding involved
in server-socket programming.
RMI is used to build distributed applications; it provides remote communication between
Java programs. It is provided in the package java.rmi.
The RMI provides remote communication between the applications using two objects stub
and skeleton.

Stub:-
The stub is an object, acts as a gateway for the client side. All the outgoing requests are
routed through it. It resides at the client side and represents the remote object. When the
caller invokes method on the stub object, it does the following tasks:
1. It initiates a connection with remote Virtual Machine (JVM),
2. It writes and transmits (marshals) the parameters to the remote Virtual Machine (JVM),
3. It waits for the result
4. It reads (unmarshals) the return value or exception,
5. It finally, returns the value to the caller
Skeleton:-

The skeleton is an object, acts as a gateway for the server side object. All the
incoming requests are routed through it. When the skeleton receives the incoming
request, it does the following tasks:

1. It reads the parameter for the remote method


2. It invokes the method on the actual remote object,
3. It writes and transmits (marshals) the result to the caller.
Architecture of an RMI Application
In an RMI application, we write two programs, a server program (resides on the server) and
a client program (resides on the client).
Inside the server program, a remote object is created and reference of that object is made
available for the client (using the registry).
The client program requests the remote objects on the server and tries to invoke its
methods.
Transport Layer − This layer connects the client and the server. It manages the existing
connection and also sets up new connections.

Stub − A stub is a representation (proxy) of the remote object at client. It resides in the client
system; it acts as a gateway for the client program.
Skeleton − This is the object which resides on the server side. stub communicates with this
skeleton to pass request to the remote object.
RRL(Remote Reference Layer) − It is the layer which manages the references made by the
client to the remote object.

You might also like