0% found this document useful (0 votes)
26 views76 pages

Chapter 06 Servlet

Ffhh

Uploaded by

yashdhawale24
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)
26 views76 pages

Chapter 06 Servlet

Ffhh

Uploaded by

yashdhawale24
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/ 76

Servlet

Servl
et
■Java servlet are the programs that run on a web
application server.
■ it act as a middle layer between requests from web
browser/ client and database/application on HTTP
server
Servl
■ Webet
applications are helper applications that resides
at web server and build dynamic web pages.
■ A dynamic page could be anything like a page that
randomly chooses picture to display or even a page
that displays the current time.
Servlet : Defined in many
ways
■Servlet is a technology that is used to create web
application.
■Servlet is an API that provides many interfaces and
classes including documentations.
■Servlet is an interface that must be implemented
for creating any servlet.
■Servlet is a class that extend the capabilities of the
servers and respond to the incoming request. It can
respond to any type of requests.
■Servlet is a web component that is deployed on the
server to create dynamic web page.
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.


CGI(common gateway
interface)

HTTPd stands for Hypertext Transfer Protocol daemon. It usually is the main software part of an HTTP server better
known as a web server.
Disadvantages of CGI

There are many problems in CGI technology:


•If number of clients increases, it takes more time for
sending response.
•For each request, it starts a process and Web
server is limited to start processes.
•It uses platform dependent language e.g. C, C++,
perl.
Advantage of Servlet

•The web container creates threads for handling the


multiple requests to the servlet.

•Threads have a lot of benefits over the Processes


such as they share a common memory area,
lightweight, cost of communication between the
threads are low.
Advantage of Servlet
Advantages of servlet over
CGI(common gateway
interface)
● Better performance: because it creates a thread for each
request not process.
● servlet executes within address space of a web
server. It is not necessary to create separate process
to handle each client request
● platform independent
•Portability: because it uses java language.
•Robust: Servlets are managed by JVM so we don't need to
worry about memory leak, garbage collection etc.
•Secure: because it uses java language
Servlet life
cycle
■Each servlet instance is loaded once.
■Each execution happens in a separate thread
■Three methods:
■init() : call only once to initialize servlet.
■service() : Call for every request.
■destroy() : call only once
■Method service() is invoked every time a request
comes. It spawns off threads to perform doGet or
doPost based on the method invoked.
Servlet life
1. Loadcycle
Servlet Class.
2. Create Instance of Servlet.
3. Call the servlets init() method.
4. Call the servlets service() method.
5. Call the servlets destroy() method.
Note: Step 1,2,3 executed only once when servlet is initially
loaded.
Step 4 executed "N"-times whenever http request comes
Step 5 executed to destroy servlet means unload servlet class
Servlet life
cycle

ilesh Vishwasrao
Servlet life
cycle
Types of
Servlet
■Generic Servlet:
■It is in javax.servlet.GenericServlet package
■It is protocol independent.
■HTTP Servlet:
■It is in javax.servlet.HttpServlet package
■Built-in HTTP protocol support.
Types of
Servlet
Generic Servlet HTTP Servlet

Package: javax.servlet Package: javax.servlet.http

It is protocol independent It is protocol dependent


servlet specifically only HTTP protocol
request- response handle.

It uses service() method for It uses methods like doPost(),


handling request-response. doGet()
The browser uses two methods to pass this
information to web server. These methods are GET Method and
POST Method.

GET Method (doGet())

•The GET method sends the encoded user information


appended to the page request. The page and the encoded
information are separated by the ?(question mark) symbol as
follows −
http://www.test.com/hello?key1 = value1&key2 = value2
POST Method
•A generally more reliable method of passing information to a
backend program is the POST method.
•This packages the information in exactly the same way as GET
method, but instead of sending it as a text string after a ?
(question mark) in the URL it sends it as a separate message.
•This message comes to the backend program in the form of
the standard input which you can parse and use for your
processing.
• Servlet handles this type of requests using doPost() method.
Servlets handles form data parsing automatically using
the following methods depending on the situation −
•getParameter() − Call request.getParameter() method to get the
value of a form parameter.
•getParameterValues() − Call this method if the parameter appears
more than once and returns multiple values, for example checkbox.
<font face="verdana" size="2px">
<form action="onGPV" method="post">
Habits :
<input type="checkbox" name="habits" value="Reading">Reading
<input type="checkbox" name="habits" value="Movies">Movies
<input type="checkbox" name="habits" value="Writing">Writing
<input type="checkbox" name="habits" value="Singing">Singing
<input type="submit" value="Submit">
</form>
</font>

•getParameterNames() − Call this method if you want a complete list


of all parameters in the current request.
DoGet DoPost

In doGet Method the parameters are appended In doPost, parameters are sent in separate line
to the URL and sent along with header in the body tag
information
Maximum size of data that can be sent using There is no maximum size for data
doGet is 240 bytes
Parameters are not encrypted Parameters are encrypted
DoGet method generally is used to query or to DoPost is generally used to update or post
get some information from the server some information to the server

DoGet is faster if we set the response content DoPost is slower compared to doGet since
length since the same connection is used. Thus doPost does not write the content length
increasing the performance

DoGet should be idempotent. i.e. doGet should This method does not need to be idempotent.
be able to be repeated safely many times Operations requested through POST can have
side effects for which the user can be held
accountable, for example, updating stored data
or buying items online.
DoGet should be safe without any side effects This method does not need to be either safe
for which user is held responsible
Servlet
API
■Servlet API consists of two important packages
that encapsulates all the important classes and
interface, namely :
■javax.servlet
■javax.servlet.http
Servlet Interface:
javax.servlet
Interfaces Description
Servlet Declare life cycle methods for servlet. To
implement this interface we have to extends
GenericServlet or HttpServlet classes.

ServletConfig Helps servlet to get initialization parameter


means startup information, basic
information about servlet.

ServletContext Allows servlet to log events and access


information about their environment
ServletRequest Used to read data from client
ServletResponse Used to sent data to client
Servlet Classes:
Classesjavax.servlet
Description
GenericServlet Used to create servlet (Protocol
independent)
ServletInputStream Provides an input stream for reading
requests from client.
ServletOutputStream This class supports an output stream
for writing responses to a client
ServletException For handling exception: Error Occurred
UnavailableException For handling exception: generate when
servlet not available
Servlet Classes :
javax.servlet.http
Classes Description
HttpServlet Used to create http servlet (Protocol
dependent)
HttpServletRequest It enables servlets to read data from an
HTTP request
HttpServletRespons It enables servlets to write data to an
e HTTP response
HttpSession It allows to read and write session data.

Cookie Cookie class allows state information to


be stored on a client machine
Servlet Interface:
Methods
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.
GenericServlet
class Servlet, ServletConfig and
■It implements
Serializable interfaces.
■It provides the implementation of all the methods of
these interfaces except the service method (You
have to write code in your servlet class for this
method).
■GenericServlet class can handle any type of
request so it is protocol-independent.
ServletConfig interface
■Object of ServletConfig created by the web
container for each servlet.
■This object can be used to get configuration
information from web.xml file.
■Advantage: No need to edit the servlet file if
information is modified from the web.xml file.
ServletConfig
interface
■public String getInitParameter(String name):
Returns the parameter value for the specified
parameter name.
■Enumeration getInitParameterNames():
Returns all the initialized parameter names.
■public String getServletName():
Returns the name of the servlet.
■public ServletContext getServletContext():
Returns an object of ServletContext.
ServletConfig
interface
ServletContext
interface
■An object of ServletContext is created by the
web container at time of deploying the project
(web application).
■This object can be used to get configuration
information from web.xml file.
■There is only one ServletContext object per web
application.
ServletContext
interface
■If any information is shared to many servlet, it is
better to provide it from the web.xml file using
the <context-param> element.
■Usage:
■ The object of ServletContext provides an interface between the
container and servlet.
■ The ServletContext object can be used to get configuration information
from the web.xml file.
■ The ServletContext object can be used to set, get or remove attribute
from the web.xml file.
■ The ServletContext object can be used to provide inter-application
communication.
ServletContext
interface
<context-param>

<param-name>dname </param-name>
<param-value> sun.jdbc.odbc.JdbcOdbcDriver
</param-value>

</context-param>
ServletContext
interface
ServletConfig Vs
Config
ServletContext
Context
One object per servlet Object is global to entire web
application
Object is created when Object is created when web
servlet class is loaded application deployed
It destroy when servlet is It will destroyed when web
destroyed or upload the class. application is un-deployed or
removed.
Config object is public to It can share information
particular servlet only. between the servlet
HttpServl
et
■It extends GenericServlet class and
implements Servlet, ServletConfig and
Serializable interface.
■It provides http specific methods such as
doGet, doPost, doHead, doTrace etc.
HttpServlet

• The most important are six doxxx methods that get


called when a related HTTP request method is used.
• The six methods are doPost, doPut, doGet, doDelete,
doOptions and doTrace.
• For instance, the doGet method is invoked when the
servlet receives an HTTP request that was sent using the
GET method.
• Of the six doxxx methods, the doPost and the doGet
methods are the most frequently used.
HttpServl
et
Implementati
on
■A Java Servlet is just an ordinary Java class
which implements the interface
■javax.servlet.Servlet;

■The easiest way to implement this interface is


to extend either the
■class GenericServlet or HttpServlet.
Exampl
e
Implementati
on
■When an HTTP request arrives at the web
server, targeted for your Servlet, the web
server calls your Servlet's service() method.

■The service() method then reads the request,


and generates a response which is sent back to
the client (e.g. a browser).
Implementation:HT
TP
■The javax.servlet.http.HttpServlet class is a
slightly more advanced base class than
the GenericServlet
■The HttpServlet class reads the HTTP request,
and determines if the request is an HTTP GET,
POST, PUT, DELETE, HEAD etc. and calls one
the corresponding method.
Implementation:
HTTP
HttpRequest:
Interface
■This interface present in
javax.servlet.http.HttpRequest

■The purpose of the HttpRequest object is to


represent the HTTP request a browser sends to
your web application.
HttpRequest:
Parameters
■Thus, anything the browser may send,
is accessible via the HttpRequest.
■We can read initialization parameters also
using HttpServletRequest object with
getInitParameter method.
HttpRequest:
Parameters
■Also we can use following code if request parameters is
send through body part of the Http request.

■If the browser sends an HTTP GET request, the


parameters are included in the query string in the URL.
■If the browser sends an HTTP POST request, the
parameters are included in the body part of the HTTP
request.
HttpRequest:
Header
■ The request headers are name, value pairs sent by the browser
along with the HTTP request.
■ The request headers contain information about e.g. what
browser software is being used, what file types the browser is
capable of receiving etc. In short, at lot of meta data around the
HTTP request.

■ Above example reads the Content-Length header sent by the


browser.
HttpRequest:
InputStream
■If the browser sends an HTTP POST request, request
parameters and other potential data is sent to the
server in the HTTP request body.
■If does not have sent data in parameters means may be
binary data, that time we will require InputStream for
accessing request body come from client.
■InputStream requestBodyInput =
request.getInputStream();
■NOTE: You will have to call this method before
calling any getParameter() method.
HttpRequest:
Session
■ It is possible to obtain the session object from the
HttpRequest object too.
■ The session object can hold information about a given user,
between requests.
■ So, if you set an object into the session object during one
request, it will be available for you to read during any
subsequent requests within the same session time scope.
HttpResponse:
Interface
■ This interface is present in java.servlet.http package.
■ The purpose of the HttpResponse object is to
represent the HTTP response of web application
sends back to the browser.
HttpResponse: Writing
HTML
■ To send HTML back to the browser, you have to
obtain the a PrintWriter from the HttpResponse
object.
HttpResponse:
Headers
■ Headers must be set before any data is written to the
response.
■ Examples:
■Syntax:
response.setHeader("Header-Name", "Header Value");
■Set Content type:
response.setHeader("Content-Type", "text/html");
■Writing text
response.setHeader("Content-Type",
"text/plain"); PrintWriter writer =
response.getWriter(); writer.write("This is
just plain text");
■Content-length
HttpResponse: Writing
Binary
Dat
a
■ We can also write binary data back to the
browser instead of text.
■ For instance, we can send an image back, a PDF file or
a Flash file or something like that.
■ First we have to set content type. And need to use
following code:
OutputStream outputStream =
response.getOutputStream();
outputStream.write(...);
HttpResponse:
Redirecting
■ We can redirect the browser to a different URL
from your servlet.
■ You cannot send any data back to the browser
when redirecting response.sendRed
irect("http://www.google.com");
Or Another servlet file call
response.sendRedirect(“HelloServ
let");
HttpSessi
on
■ The HttpSession object represents a user session.
■ A user session contains information about the
user across multiple HTTP requests.
■ When a user enters your site for the first time, the user
is given a unique ID to identify his session by.
■ This ID is typically stored in a cookie or in a request
parameter.
HttpSessi
on
■We can store values in the session object, and retrieve
them later. Do it in following way:
session.setAttribute("userName", "theUserName");
■This code sets an attribute named "userName", with
the value "theUserName".
■To read the value again:
String userName = (String) session.getAttribute("userName");

■Values stored in the session object are stored in the


memory of the servlet container.
HttpSession: In
■ If we Clusters
have an architecture with 2 web servers in a
cluster, keep in mind that values stored in the session
object of one server, may not be available in the
session object on the other server.
■ The solution to this problem would be one of:
■ Do not use session attributes.
■ Use a session database, into which session attributes are
written, and from which it is read.
■ Use sticky session, where a user is always sent to the same
server,
throughout the whole session.
HttpSession:
Example
■Create one HTML file: index.html which send user name
and password to the servlet file.

■Create two servlet file, one will save user name into
session and that session information is send to another
servlet. This example shows the session tracking.
RequestDispatc
her
■ The RequestDispatcher class enables your servlet to "call"
another servlet from inside another servlet.
■ We can obtain a RequestDispatcher from the
HttpServletRequest object.

■ The above code obtains a RequestDispatcher targeted at


whatever Servlet (or JSP) that is mapped to the URL
/anotherUrl.simple.
RequestDispatc
her
■ You can call the RequestDispatcher using either its
include() or forward() method.

■ The forward() method intended for use in forwarding the


request, meaning after the response of the calling servlet has
been committed. You cannot merge response output using this
method.
■ The include() method merges the response written by the
calling servlet, and the activated servlet. This way you can
achieve "server side includes" using the include().
Servlet: Load on start
up
■ The <servlet> element has a sub-element called
<load-on-startup> which you can use to control when the servlet
container should load the servlet.

■ If you do not specify a <load-on-startup> element, the servlet


container will typically load your servlet when the first request
arrives for it.

■ By setting a <load-on-startup> element, you can tell the servlet


container to
load the servlet as soon as the servlet container starts.
■ Remember, the servlets init() method is called when the servlet is
loaded.
WEB.XML
1. Go to C:\Program Files\apache-tomcat-8.5.84\Webapps\examples\WEB-INF
Edit web.xml and type following code and save it.
<servlet>
<servlet-name>MyServlet1</servlet-name>
<servlet-class>MyServlet1</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>MyServlet1</servlet-name>
<url-pattern>/sample/MyServlet1</url-pattern>
</servlet-mapping>

2. Create Sample folder in C:\Program Files\apache-tomcat-8.5.84\Webapps


3. In Sample folder create WEB-INF Folder
4. In WEB-INF Folder create classes Folder
5. In classes Folder create .java and . class file
6. In WEB-INF Folder copy web.xml file
7. In Sample folder copy .java and . class file
8. Copy .java and . class file in C:\ProgramFiles\apache-tomcat-8.5.84\Webapps\
examples\WEB-INF\classes
import java.io.*; /*public String getServletInfo()
import javax.servlet.*; {
import javax.servlet.http.*; return "Our first Servlet";
}
public class MyServlet1 implements */
Servlet
{ /*public ServletConfig getServletConfig()
private ServletConfig config; {
return config;
/*public void init(ServletConfig sc) }*/
{
System.out.println("Initializing the /*public void destroy()
Servlet"); {
} System.out.println("Destroying the
*/ servlet");
public void service(ServletRequest }*/
request, ServletResponse response) }
throws ServletException,
IOException 9. Start apache tomcat by using
{ command- C:\ProgramFiles\apache-
PrintWriter out = tomcat-8.5.84\bin>startup on cmd prompt
response.getWriter();
out.println("Hello there!"); 10. Open browser and type URL
//System.out.println("Putting the http://localhost:8080/examples
Servlet in service"); /sample/filename_without_extension
Output:
Cooki
e
■HTTP Cookies are little pieces of data that a web
application can store on the client machine of users
visiting the web application.
■Typically up to 4 kilo bytes(KB) of data can be store.
■We can write cookies using HttpServletResponse object:
■Example:
Cookie cookie = new Cookie("myCookie",
"myCookieValue"); response.addCookie(cookie);
Cooki
e each request is considered as a new request.
■By default,
■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.
Cookie:
Types
■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 sign-out or clear cookies/cache memory of
browsers.
Cookie:
Pros/Cons
■Advantages:
■Simplest technique of maintaining the state.
■Cookies are maintained at client side.

■Disadvantages
■It will not work if cookie is disabled from the browser.
■Only textual information can be set in Cookie object.
Cookie:
Constructor
■javax.servlet.http.Cookie class provides the
functionality of using cookies. It provides a lot of
useful methods for cookies.

Constructor Description
Cookie() constructs a cookie.
Cookie(String name, String value) constructs a cookie with a specified
name and value.
Cookie:
Methods
■Useful
methods:
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.

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.


Cookie:
Methods
■Other methods:
■public void addCookie(Cookie ck):method
of HttpServletResponse interface is used to
add cookie in response object.
■public Cookie[] getCookies():method of
HttpServletRequest interface is used to return
all the cookies from the browser.
Cookie: How to
create?
■Creating cookie object
Cookie ck=new
Cookie("user",”Sandip");

■Adding cookie in the response


response.addCookie(ck);//
Cookie: For delete
Cookies
■Deleting value of cookie
Cookie ck=new Cookie("user","");

■Changing the maximum age to 0


seconds
ck.setMaxAge(0);

■Adding cookie in the response


response.addCookie(ck);
Cookie: To get
Cookies
Cookie ck[]=request.getCookies();
for(int i=0;i<ck.length;i++)
{
out.print("<br>"+ck[i].getName()+"
"+ck[i].getValue());
//printing name and value of cookie
}
Cookie:
Example
Cookie:
Example
■Create one Html file which send user name
to first servlet.
■First servlet file set cookies of that user
name and call second servlet file.
■Second servlet file retrieve name of user
from cookies instead of from session.
Session Cookies
Sessions are server-side files that store the Cookies are client-side files that contain user
user information information on a local computer.

A session stores the variables and Cookies are stored on the user's
their values within a file in a computer as a text file.
temporary directory on the server.
The session ends when the user Cookies end on the lifetime set by
logout from the application or closes the user.
his web browser.
It can store an unlimited amount of It can store only limited data.
data.
We can store as much data as we The maximum size of the browser's
want within a session, but there is a cookies is 4 KB.
maximum memory limit, which a
script can use at one time, and it is
128 MB.

Sessions are more secured Cookies are not secure, as data is


compared to cookies, as they save stored in a text file, and if any
data in encrypted form. unauthorized user gets access to our
system, he can temper the data.

You might also like