8/2/2019 Servlets by Kamalakar Dandu
1/77
8/2/2019 Servlets by Kamalakar Dandu
2/77
Objectives
Understand the Servlet Architecture.
Compare Servlet & Other Similartechnologies.
Understand the Servlet Life Cycle. Handle Request & Response.
Generate Dynamic HTML.
Handle Sessions.
8/2/2019 Servlets by Kamalakar Dandu
3/77
Common Gateway Interface (CGI)
ColdFusion (Allaire)
Active Server Pages (ASP)
Server-Side JavaScript (SSJS) Personal Home Page tools (PHP)
Java Servlets
JavaServer Pages
Evolution of Dynamic Content Tech.
8/2/2019 Servlets by Kamalakar Dandu
4/77
Main Process
CGI-Based Web Server
Request for CGI 1
Request for CGI 2
Request for CGI 3
Child Process for CGI 1
Child Process for CGI 2
Child Process for CGI 3
The CGI Life Cycle
8/2/2019 Servlets by Kamalakar Dandu
5/77
Java Servlet A Java program that
extends the functionality of a Web server, generating dynamic
content and interacting with Web clients using a request
response paradigm.
An extensible Web technology that uses template data,
custom elements, scripting languages, and server-side
Java objects to return dynamic content to a client.
Typically the template data is HTML or XML elements.
The client is often a Web browser.
J2EE 1.2 Architecture
8/2/2019 Servlets by Kamalakar Dandu
6/77
8/2/2019 Servlets by Kamalakar Dandu
7/77
8/2/2019 Servlets by Kamalakar Dandu
8/77
8/2/2019 Servlets by Kamalakar Dandu
9/77
Advantages of Servlets
Java objects which extend thefunctionality of a HTTP server(a big plus). Dynamic customization of content Platform and server independent No CGI limitations
better performance Easier to write than CGI code
no need to parse headers and get info(all that is done by the HttpServlet class)
No Networking restrictions (like applets) Do not create a new process (or Servlet for
every request) Servlets can persist over time
8/2/2019 Servlets by Kamalakar Dandu
10/77
Server Extensions
Enhance or Change the base functionality
of the server, allowing the server to handle tasks
that were once relegated to external CGI
programs.
8/2/2019 Servlets by Kamalakar Dandu
11/77
The Power of Servlets
Portability
Power
Efficiency and Endurance
Safety
Elegance
Integration
Extensibility and Flexibility
8/2/2019 Servlets by Kamalakar Dandu
12/77
8/2/2019 Servlets by Kamalakar Dandu
13/77
The Servlet Life Cycle A web server
communicates with
a Servlet through asimple interface,
javax.servlet.Servlet. This interface
consists of threemain methods:
init()
service()
destroy()and two ancillary
methods:
getServletConfig()
getServletInfo()
http://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.html8/2/2019 Servlets by Kamalakar Dandu
14/77
Servlet Life Cycle (contd)
Request for Servlet1
Request for Servlet2
Request for Servlet1
Main Process
JVM
Servlet1
Servlet2
Thread
Thread
Thread
Java Servlet-based Web Server
Servlet initialized once; reused until destroyed andgarbage collected.
8/2/2019 Servlets by Kamalakar Dandu
15/77
Servlet Life Cycle (contd)
8/2/2019 Servlets by Kamalakar Dandu
16/77
Life Cycle Of A Servlet (contd)
A servlet is constructed and initialized. It then services zeroor more requests until the service that it extends shuts down
Initialized only once, stays resident in memory while
servicing requests
Multiple threads of execute service(), one for each client
connection
The servlet interface defines the life cycle methods :
init()
service()
destroy()
8/2/2019 Servlets by Kamalakar Dandu
17/77
init() Method
Called by server immediately after servlet isinstantiated
Called only once Servlet creates and initializes the resources
needed for handling requests
public void init(ServletConfig config) throwsServletException;
ServletException - thrown when servlet cannot
initialize necessary resources
8/2/2019 Servlets by Kamalakar Dandu
18/77
service() Method
It is the heart of the servlet.
It handles all requests sent by a client.
Each request message from a client results in a single
call to the servlet's service() method. It reads the request and produces the response message
public void service(ServletRequest req,
ServletResponse res) throws ServletException,IOException;
8/2/2019 Servlets by Kamalakar Dandu
19/77
destroy() Method
This signifies the end of a servlets life.
Its also a good place to save any persistent information
that will be used the next time the servlet is loaded.
It is called to allow the servlet to clean up any
resources.
Public void destroy();
8/2/2019 Servlets by Kamalakar Dandu
20/77
Servlet Life Cycle (contd)
service()
destroy()
init()
Servlet loaded on demand (first time
user accesses the servlet). Once loaded theservlet is in memory
Unloaded on closing server;
manual unloading
Client requestsarrive
each client request creates a
new thread with service
8/2/2019 Servlets by Kamalakar Dandu
21/77
Servlet Interface
Servlets Classes / Interfaces are available in packages
(in java servlet development kit)
javax.servlet.http
javax.servlet
8/2/2019 Servlets by Kamalakar Dandu
22/77
Servlet Interface (contd)
8/2/2019 Servlets by Kamalakar Dandu
23/77
KEY : implemented by subclass
Server GenericServletsubclass
service()request
response
A generic servlet handling a request
GenericServlet Class
8/2/2019 Servlets by Kamalakar Dandu
24/77
HEAD requestresponse
KEY : implemented by subclass
Web ServerHttpServletsubclass
service()
GET requestresponse
A Http Servlet Handling a Request
POST requestresponse
doGet()
doPost()
doHead()
HTTP request
Implementation of doGet() doPost() is toreturn an error to the calling client ifservlet does not override these methods.
8/2/2019 Servlets by Kamalakar Dandu
25/77
Generic servlet vs httpservlet
init
destroy
service
HttpServlet
doGet(...)
doPost(...)
extends
Generic Servlet
doOptions()
doDelete()
doTrace()doPut()
8/2/2019 Servlets by Kamalakar Dandu
26/77
8/2/2019 Servlets by Kamalakar Dandu
27/77
What does the Server Receive
server client
http://www.mcp.com/index.html
GET /index.html HTTP/1.0
Searching for www.mcp.comFound www.mcp.com
Server receives only oneof the HTTP requestmethods (Get/Post)
Servlet programmers must provideimplementations for these requests
Web server recieves
8/2/2019 Servlets by Kamalakar Dandu
28/77
Web Server
HttpServletsubclass
service()
doGet()
doPost()
doHead()
Web server recievesGET /servlet/myHelloServlet
Web server uses logic:
myHelloServlet is loaded. If not , then load the servlet.
call service method (already implemented in HttpServlet)(it checks the request type and correspondingly calls the
doGet() or doPost() method )
GET/servlet/
myHelloServlet
HTTP/1.0
Check request typeit is GET
hence call doGet()
8/2/2019 Servlets by Kamalakar Dandu
29/77
javax.servlet
ServletInputStream
ServletOutputStream
GenericServlet
InputStream
OutputStream
java.io
java.lang
Serializable
SingleThreadModel
ServletResponse
ServletRequest
ServletContext
ServletConfig
Servlet
InterfaceABSTRACT CLASSKEY
Object
Class
ServletExceptionException UnavailableException
extends implements
8/2/2019 Servlets by Kamalakar Dandu
30/77
ServletInputStream ServletOutputStream
GenericServlet
ServletResponseServletRequest
Serializable
ServletConfig
Servlet
InterfaceABSTRACT CLASSClass implements
service(req, res)javax.servlet.*
8/2/2019 Servlets by Kamalakar Dandu
31/77
ServletContext / ServletConfig
ServletConfig used to get initialization parameters
getServletContext()
String getInitParameter(String)
Enumeration getInitParameterNames()
ServletContext useful for logging & finding out about the
other servlets
Servlet getServlet(String)
Enumeration getServlets()
Enumeration getServletNames() void log(String)
void log(Exception, String)
8/2/2019 Servlets by Kamalakar Dandu
32/77
GenericServlet Serializable
InterfaceABSTRACT CLASSClass implements
HTTPServlet
extends
javax.servlet.http.*
8/2/2019 Servlets by Kamalakar Dandu
33/77
Servlet Architecture
HTTPServlet
Servlet
Interface class extends
Methods formanaging a servlet and
communicating with
clients
8/2/2019 Servlets by Kamalakar Dandu
34/77
Servlet
GET request
response
ServletRequest
ServletResponse
Encapsulates communicationfrom client to server
Encapsulates communicationfrom server to client
8/2/2019 Servlets by Kamalakar Dandu
35/77
package codecamp;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;Public class ServletGet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse
response) throws ServletException,
IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("FirstServlet");
out.println("Hello Code Camp!
");
}
}
A Simple Code Example
8/2/2019 Servlets by Kamalakar Dandu
36/77
Example
Write the following html file: mydisplay.html calling servlets
Click on the button call servletGet and note that theearlier servlet is called.
Eg: mydisplay.htmlNOTE:User clicked on button, and the browser thengenerated the GET method based on action settings.
Generating GET by clicking a
8/2/2019 Servlets by Kamalakar Dandu
37/77
Generating GET by clicking a
button on browser
server client
http://localhost//mydisplay.html
GET /mydisplay.html HTTP/1.0
Searching for localhostFound localhost
call servletGet
GET /servlet/servletGet HTTP/1.0
8/2/2019 Servlets by Kamalakar Dandu
38/77
Example
Modify only the following line in html file:mydisplay.html
Click on the button call servletGet and note whathappens.
NOTE:User clicked on button, and the browser then
generated the POST method based on action settings.
NOTE: the servlet servletGet did not contain a doPost
method and hence got the error. Rename doGet() to
doPost() and it would then work.
T f i i f f b t S l t
8/2/2019 Servlets by Kamalakar Dandu
39/77
Transferring info from browser to Servlets
Generally in web pages, users fill up a formwith fields.
Browser communicates with server (servlets)through GET and POST methods
GET requests : Getting information Appended to the URL in a query string ( limited amount of data)
.../servlet/ViewCourse?name=servlets_codecamp Can be bookmarked and emailed
POST requests: Sending information Send any amount of data .../servlet/PlaceOrderProcess Can Not be bookmarked and emailed. Use POST for things like placing an order.
8/2/2019 Servlets by Kamalakar Dandu
40/77
Common Requests: GET and POST
GET Getting information
Appended to the URL in a query string ( limitedamount of data)
.../servlet/ViewCourse?name=servlets_codecamp Can be bookmarked and emailed
POST requests:
Sending information
Send any amount of data
.../servlet/PlaceOrderProcess
Can Not be bookmarked and emailed.
Use POST for things like placing an order.
8/2/2019 Servlets by Kamalakar Dandu
41/77
Example
Write a html with three text fields for name, id and location,
with a submit button. Set the form method as GET, and
action as servlet/servletGetParam
Eg: servlet_get_HTML.html
Write a servlet with doGet() method. In the doGet() method
read the parameters and then send it back to the browser for
display
Eg: servletGetParam.java
8/2/2019 Servlets by Kamalakar Dandu
42/77
Example
Write a html with three text fields for name, id and location,with a submit button. Set the form method as POST, and
action as servlet/servletGetParam
Eg: servlet_post_HTML.html
Write a servlet with doPost() method. In the doPost() method
read the parameters and then send it back to the browser fordisplay
Eg: servletPost.java
8/2/2019 Servlets by Kamalakar Dandu
43/77
Interface ServletRequest
information about the client name of the host and the IP address of client
parameters sent from the client browser
scheme used by the browser to communicate
to servlet (eg. http; https; ftp;..) protocol used by client (eg. ftp)
access to the ServletInputStream (whichallows servlet to read binary data from the
client ) information about server
name of the server
port used by the server
8/2/2019 Servlets by Kamalakar Dandu
44/77
ServletRequest
Subclass ServletRequest to provide protocol specificinformation
Example: HTTPServletRequest (extends ServletRequest)supports methods to retrieve more protocol specificheaders (getMethod() to identify the type of request)
j l t S l tR t
8/2/2019 Servlets by Kamalakar Dandu
45/77
javax.servlet.ServletRequest
ServletRequestString getContentType()ServletInputStream getInputStream()String getParameter(String)Enumeration getParameterNames()
String getProtocol()BufferedReader getReader()String getRemoteAddr()String getServerName()int getServerPort()
String getScheme()String getRealPath()String getCharacterEncoding()Object getAttribute()
class Name
public
abstract
methods
8/2/2019 Servlets by Kamalakar Dandu
46/77
interface HTTPServlet
Information from clientadditional path info (sent along with request)
eg /servlet/myservlet/dict/defn.txt
/dict/defn.txt is the additional info to the servlet
myservlet within your servlet use getPathInfo() (null if no such
data is available)
what was requested (file/ servlet/)
HTTP headers sent by the client
Connection, User-Agent, host, Accept, Accept-language, Accept-Charset
8/2/2019 Servlets by Kamalakar Dandu
47/77
HTTP Headers
General : Information not related to Client, Server or
HTTP protocol.
Request : Preferred Document formats and server
parameters.
Response : Information about the server.
Entity : Information on the data that is being sent
between the client and server.
j l t htt Htt S l tR t
8/2/2019 Servlets by Kamalakar Dandu
48/77
javax.servlet.http.HttpServletRequest
HTTPServletRequest extends ServletRequest
Enumeration getHeaderNames()long getDateHeader(String)String getPathInfo()
String getQueryString()String getRemoteUser()String getAuthType()Cookie[ ]getCookies()String getRequestURI()String getServletPath()String getSession()boolean isRequestedSessionIdFromCookie()boolean isRequestedSessionIdFromUrl()
Class Namepublic
abstract
methods
8/2/2019 Servlets by Kamalakar Dandu
49/77
Example
Write a servlet that implements the doGet() method. Capture the
information encapsulated in the request object (in ServletRequest
and HTTPServletRequest), and send this info back to the client.
Eg: helloservletGet.java
8/2/2019 Servlets by Kamalakar Dandu
50/77
ServletResponse Interface
Allows the servlet to reply to the client
Allows the servlet to set the content length and MIME
type
Provides a handle to ServletOutputStream (or Writer)to send data to the client
Subclass HTTPServletResponse supports methods to
set more protocol specific headers
8/2/2019 Servlets by Kamalakar Dandu
51/77
javax.servlet.ServletResponse
ServletResponse
void setContentLength(int)void setContentType(String);ServletOutputStream getOutputStream()PrintWriter getWriter()String getCharacterEncoding(String)
Class Name
publicabstract
methods
javax servlet http
8/2/2019 Servlets by Kamalakar Dandu
52/77
javax.servlet.http.
HttpServletResponse
HTTPServletResponse
void addCookie(http.Cookie)boolean containsHeader(String);String encodeURL(String)String encodeRedirectURL(String)String encodeUri(String)String encodeRedirectUri(String)void setHeader(String,String)void setIntHeader(String,int)
void setDateHeader(String,long)void setStatus(int,String)void sendError(int,String)void sendRedirect(String)
Class Name
public
abstract
methods
R di i
8/2/2019 Servlets by Kamalakar Dandu
53/77
Redirecting
Redirection can be set using the following methods in theHttpServletResponse class
setStatus(status code)
status codes available in the HttpServletResponse class as
static variables setHeader(Location, give new site location here)
the new location must be an absolute url path
setHeader(Refresh, 3) will tell the browser for 3 seconds
before refreshing the page setHeader(Refresh, 3; URL=..) will tell the browser for 3seconds before going to the new location specified in thecommand.
8/2/2019 Servlets by Kamalakar Dandu
54/77
Generating HTML
Hardcoded in the program (servletGet.java)
Using an HTML generator (require additional
software; html generation classes)
Using an HTML generator creatively
Eg : ServletGet.java
8/2/2019 Servlets by Kamalakar Dandu
55/77
Redirecting a Request
Servlet can use status codes and headers to inform a
client to use another URL. It is useful when
document (html file) has moved.
load balancing is required. (one machine candistribute the load to many machines)
8/2/2019 Servlets by Kamalakar Dandu
56/77
Abstract class HTTPServlet
HTTPServlet extends GenericServlets implementsSerializable
void doGet(HttpServletRequest, HttpServletResponse)long getLastModified(HttpServletRequest);
void doPost(HttpServletRequest, HttpServletResponse)void doPut(HttpServletRequest, HttpServletResponse)void doDelete(HttpServletRequest, HttpServletResponse)void doOptions(HttpServletRequest, HttpServletResponse)void doTrace(HttpServletRequest, HttpServletResponse)
void service(HttpServletRequest, HttpServletResponse)public void service(ServletRequest, ServletResponse)
class Name
protected
methods
All methods throws ServletException and IOException
The service method supports HTTP 1.0protocol. This method dispatches each requestto the method designed to handle it.
8/2/2019 Servlets by Kamalakar Dandu
57/77
Overriding Methods
Servlet writer who wants to handle the GET and the
HEAD (HTTP protocol) must override the doGet()method in the servlet.
Similarly override doPost() method to handle POST request
doPut() method to handle PUT requests
doDelete() method to handle DELETE requests
8/2/2019 Servlets by Kamalakar Dandu
58/77
Notes
Servlets are fundamentally multithreaded, hence can
run multiple service() methods.
Therefore the code for service method must be thread
safe. If you do not want a multithreaded server then one
must implement the SingleThreadedModel interface.
8/2/2019 Servlets by Kamalakar Dandu
59/77
Example
Write a counter servlet that counts the number of clients
served.
Eg: MyCounterServ.java
Modify the above servlet so that if many users are accessing
the variable count, it should be synchronized.
Eg: MyCounterServSyn.java
E l
8/2/2019 Servlets by Kamalakar Dandu
60/77
Example
Write a servlet that informs the client that the site has moved,
and allow let the browser go to the new url automatically after
9 seconds.
Eg: RelocateServlet.java
R t Di t h
8/2/2019 Servlets by Kamalakar Dandu
61/77
Request Dispatcher
The basic use of a RequestDispatcher:
One can effectively use the RequestDispatcher to call a JSP
from a servlet or a servlet from another servlet.
RequestDispatcher rd =
getServletContext().getRequestDispatcher("/welcome.jsp");
rd.include(request, response);
S di M l i di C
8/2/2019 Servlets by Kamalakar Dandu
62/77
Sending Multimedia Content
To send an image that is available with the server to the
client
open a stream to the client browser
open the local image file
read block of bytes/ or byte by byte of image
send information to server by writing to the stream
E l
8/2/2019 Servlets by Kamalakar Dandu
63/77
Example
Write a serlvet that sends an image to the browser.
Image file must be on the server system.
Eg: servletImage.java
Problem: If we write 2 images to theapplication, it will read only the first one.
Hence, one can send only one image at atime.
Example
8/2/2019 Servlets by Kamalakar Dandu
64/77
Example
Write a serlvet that sends 2 tags to the
client. The client would load one image after another and
display both of them.
Eg: servletImageHTML.java
Solution: send the html tag , and the
browser will open connection and get the informationfrom server. This way any number of images can be
passed.
Note: All the data to be sent is stored in a
byteArrayOutputStream and sent all at once. This isbuffering but could slow down when lot of information is
being sent to the client.
User Authentication
8/2/2019 Servlets by Kamalakar Dandu
65/77
User Authentication
Specify in the resource list
servlet resource/ and what type of authentication
once set, then the browser gives a dialog box and
then sends the name and password to the servlet
Eg: secureServlet.java
Session Tracking
8/2/2019 Servlets by Kamalakar Dandu
66/77
Session Tracking
Mechanism to maintain a state about a series of
requests from the same user (request originating from
same browser)
Sessions are shared across servlets
HttpSession Object
Can Store (name, value) Pairs.
Persistence and disk swapping through Object
Serialization.
Works across protocols (HTTP/HTTPS).
Session validity, Creation time etc.
Session Tracking (contd)
8/2/2019 Servlets by Kamalakar Dandu
67/77
Session Tracking (contd)
procedures in session tracking get a HttpSession object for a user
HttpSession ss = new HttpSession(true)
true means that if it a new session create a new
session object, otherwise get session id. store/get data from the HttpSession object
void ss.putValue(String name, Object val)
Object ss.getValue(String name)
void ss.removeValue(String name) Invalidate the session
ss.invalidate();
Count Example using Session
8/2/2019 Servlets by Kamalakar Dandu
68/77
Count Example using Session
Write a servlet that uses session api to track the number of
times a user has visited the site.
Eg: SessionDemo.java
W f S i T ki
8/2/2019 Servlets by Kamalakar Dandu
69/77
Ways of Session-Tracking
Hidden Form Fields
Persistent Cookies
Servlet API
8/2/2019 Servlets by Kamalakar Dandu
70/77
Security Issues
The Servlet Sandbox
Access Control Lists (ACLs)
8/2/2019 Servlets by Kamalakar Dandu
71/77
Servlet Sandbox
Itis an area where Servlets are given restricted
authority on the server.
They may not have access to the file system ornetwork, or they may have been granted a more
trusted status.
It is up to the web server administrator to decide
which servlets are granted this status.
A C t l Li t
8/2/2019 Servlets by Kamalakar Dandu
72/77
Access Control Lists
An ACL is a list of users who are allowed to perform a
specific function in the server.
The list specifies:
What kind of access is allowed
What object the access applies to
Which users are granted access
8/2/2019 Servlets by Kamalakar Dandu
73/77
Servlet Environment Inter-Servlet Communication
How to call a method of another Servlet
Servlet Environment (contd)
8/2/2019 Servlets by Kamalakar Dandu
74/77
Servlet Environment (contd)
Communication with Active Server ResourcesHow to call another Servlet (or any other kind of
active resource) to process a request
Accessing Passive Server Resources
How to access a resource in the server's document
tree
Accessing Servlet Resources
How to access resources which belong to a Servlet
Sharing Data Between Servlets
How to share data between Servlets
Invoking a Servlet From an Applet
8/2/2019 Servlets by Kamalakar Dandu
75/77
g pp
HTTP Request thru DataOutput created by
URLCorrection object
Formatted results thru DataInputStream object
created by URLConnection objectSQL Query
ResultSet Object
Exercise (contd )
8/2/2019 Servlets by Kamalakar Dandu
76/77
Exercise (contd..)
20. Due to the implementation of the application on theAWT framework it is required to install the JRE software
& the required application components on each machine
which needs to communicate with the application. A better
alternative would be to implement the same in a http basedserver architecture,(repeat exercises 1 to 5 here)[20]
8/2/2019 Servlets by Kamalakar Dandu
77/77
ThankQ