Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
SERVLETS
2
Introduction to Servlets
• Servlets are server side components written in Java that
handles the messaging between client and server
Introduction to Servlets
•
4
Introduction to Servlets
The basic flow is this:
2. The server instantiates (loads) the servlet and creates a thread for
the servlet process. Note the servlet is loaded upon the first
request; it stays loaded until the server shuts down.
A Servlet’s Job
• Read explicit data sent by client (form data)
• Powerful
Can take advantage of all Java APIs
• Persistent
Enables a Java servlet to handle multiple request. Once a servlet is
loaded in the Web server memory, it can handle multiple request
without any need of recompiling the Java servlet.
7
• Integration
• Servlets are tightly coupled with web server. For example, a servlet
can use the server to translate file paths, perform logging, check
authorization
• Efficiency
• A servlet is capable of handling different clients concurrently. In order
to handle multiple request from clients, servlet creates individual
threads
8
Servlet Container
• Servlet container (also known as servlet engine) is a runtime
environment that resides in the server and manages servlets
• The API encases requests as objects so the server can pass them to
the servlet; the responses are similarly encapsulated so the server
can pass them back to a client.
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
10
ServletRequest HttpServletRequest
ServletResponse HttpServletResponse
javax.servlet.* javax.servlet.http.*
11
HTTP REQUEST
• The http request encapsulates all information from the client request.
• It specifies the manner that the servlet expects to receive from the web
server the collection of data submitted by the user
12
HTTP Response
After receiving and interpreting a http request message, a server
responds with an HTTP response message
Servlet Architecture
• A servlet is any class that either implement the Servlet interface or
extend a class that implements the Servlet interface
Servlet Architecture
Servlet
GenericServlet
interface
Interface
class implements
HttpServlet extends
doGet()
class doPost()
...
extends
Override one or more of:
doGet()
class doPost()
...
18
Servlets Life-Cycle
New Destroyed
• The Web container
manages the life cycle init()
Running
destroy()
of servlet instances
• The life-cycle methods service()
...()
• These objects provide access to input and output streams that allow
the servlet to read data from the client and send data to the client
Handling multithreading
• When there are simultaneous requests to a servlet, the server handles
each client request by creating a new thread for each request.
• This thread is used again and again each time the same client makes
a request to the servlet
23
Creating a Servlet
Extend HTTPServlet
Implement doGet
Implement doPost
The methods
should get an input (the HTTP request)
Should create an output (the HTTP response)
24
HttpServlet Class
• The methods of HttpServletRequest make it easy to access the
data supplied as part of the request
• It has got methods by which you can find out about incoming
information such as form (query) data, HTTP request headers, and
the client’s hostname
• It lets you obtain a PrintWriter with which you send the document
content back to the client.
26
HttpServlet Request
Handling
Web
Server
27
HttpServletRequest Interface
• When a servlet is asked to handle a request, it typically needs specific
information about the request so that it can process the request
appropriately
• The Web server that executes the servlet creates an request object that
implements HttpServletRequest and passes this to the servlet's
service method (which, in turn, passes it to doGet or doPost).
• With this object, the servlet can determine the actual request (e.g.,
protocol, URL, type), access parts of the raw request (e.g., headers,
input stream), and get any client-specific request parameters (e.g.,
form variables, extra path information)
28
HttpServletRequest Interface
METHODS
• String getParameter( String name )
Returns the value associated with a parameter sent to the servlet as
part of a GET or POST request
• Enumeration getParameterNames()
Returns the names of all the parameters sent to the servlet as part of
a POST request
• Cookie[] getCookies()
returns an array of Cookie objects stored on the client by the server.
Cookies can be used to uniquely identify clients to the servlet
29
HttpServletRequest Interface
• String getHeader()
returns a String if the specified header was supplied on this request.
HttpServletResponse Interface
• In order to do anything useful, a servlet must send a response to each
request that is made to it.
HttpServletResponse Interface
• Methods
• void addCookie( Cookie cookie ) -Used to add a Cookie to the
header of the response to the client
HttpServletResponse Interface
• PrintWriter getWriter() -Obtains a character-based output stream
enabling text data to be sent to the client
Example
HelloForm.html
<html><body>
<form method="GET" action="HelloServlet">
Please enter your name:
<input type="text" name="user_name">
<input type="submit" value="OK">
</form>
</body></html>
34
HelloServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String userName = request.getParameter("user_name");
35
HelloServlet.java
out.println("<html><head>");
out.println("\t<title>Hello Servlet</title>");
out.println("</head><body>");
out.println("\t<h1>Hello, " + userName + "</h1>");
out.println("</body></html>");
}
}
36
Servlet:Example
37
Servlet:Example
38
Session Tracking
What is a session?
A session is a conversation between the server and a client, and the
conversation consists series of continuous request and response
3.Second request
1.request
2.response
client server
39
Session Tracking
Why should a session be maintained?
• As HTTP is a stateless protocol, information is not automatically saved
between HTTP requests
• There are many situations in which we need to shared data between the
servlets which are successively invoked during a session.ie there is a need
to maintain the conversational state. This is done by session tracking
• Eg: A shopping cart application in which the client keeps on adding items
into his cart using multiple requests
Session Tracking:Cookies
• A web browser, is expected to support twenty cookies per host, of at
least four kilobytes each
• The browser does nothing with cookies, other than storing them and
passing them back
• Disadvantage is that, the users can opt to disable cookies using their
browser preferences. In such case, the browser will not save the
cookie at client computer and session tracking fails.
42
Session Tracking:Cookies
•
43
• Cookies are saved one at a time into HTTP response headers, using the
addCookie() method in HttpServletResponse.
• void setMaxAge(int s)
• int getMaxAge()
• String getName()
• String getValue()
• void setValue(String s)
45
out.println("<HTML><HEAD><TITLE>");
out.println(" Use of cookie in servlet");
out.println("</TITLE></HEAD><BODY BGCOLOR='cyan'>");
out.println(" <b>This is a Cookie example</b>");
out.println("</BODY></HTML>");
out.close();
}
}
Session API
• Using sessions in servlets is quite straightforward, and involves:
• If you want to know if this is a new session, call the isNew() method
Storing Data In The Session
• Once you have got access to a session object, it can be used to store
and retrieve values.
• It can be used to transport data between requests for the same user
and session
session.removeAttribute("name");
Extracting Data From The Session
• The session object works like a HashMap
• Enables storing any type of Java object
• Objects are stored by key (like in hash tables)
Integer accessCount =
(Integer) session.getAttribute("accessCount");
Enumeration attributes =
request.getAttributeNames();
Getting Additional Session Information
• A session can be uniquely identified using a unique identifier
assigned to this session, which is called session id.
public String getId();
Session Timeout
• We can get the maximal session validity interval
(in seconds)
• A negative value specifies that the session should never time out
53
Terminating Sessions
• To terminate session manually use the method:
public void invalidate();