Sei sulla pagina 1di 53

19-Jan-18

SERVLETS
2

Introduction to Servlets
• Servlets are server side components written in Java that
handles the messaging between client and server

• Servlets can respond to client requests by dynamically


constructing a response that is sent back to the client.

• Because servlets are written in the Java programming


language, they have access to the full set of Java APIs.

• They are ideal for implementing complex business application


logic and especially for accessing data elsewhere
3

Introduction to Servlets

4

Introduction to Servlets
The basic flow is this:

1. The client sends a request to the server.

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.

3. The server sends the request information to the servlet.

4. The servlet builds a response and passes it to the server.

5. The server sends the response back to the client.


5

A Servlet’s Job
• Read explicit data sent by client (form data)

• Read implicit data sent by client(http request headers)


Request header contains the details of what the browser wants and will
accept back from the server. The request header also contains the
type, version and capabilities of the browser that is making the request
so that server returns compatible data.

• Generate the results

• Send the explicit data back to client (HTML)

• Send the implicit data to client(http response headers)


The response header contains the date, size and type of file that the
server is sending back to the client and also data about the server itself
6

Why Use Servlets?


• Portability
Since they are written in java, Servlets enable you to do server-side
programming which is platform independent.

They are portable across platforms and across different Web


servlets

• 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

Why Use Servlets?


• Safety
• Strong type-checking: Servlets inherit the strong type safety of the
Java language.

• Memory management: Java's automatic garbage collection and lack of


pointers mean that servlets are generally safe from memory
management problems

• 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

• When the Web server receives a request that is for


a servlet, the request is passed to the servlet container

• Container is responsible for instantiating, invoking, and


destroying servlet components.

• The container makes sure the servlet is loaded and calls it

• When the servlet is finished, the container reinitializes itself and


returns control to the Webserver
9

The Servlet API


• The Java Servlet API is a set of classes and interfaces that define a
standard interface between a Web client and a Web servlet.

• 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.

• These interfaces and classes are grouped into two packages:


javax.servlet, and javax.servlet.http.

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

The Servlet API


ServletConfig

Servlet GenericServlet HttpServlet

ServletRequest HttpServletRequest

ServletResponse HttpServletResponse

javax.servlet.* javax.servlet.http.*
11

HTTP REQUEST
• The http request encapsulates all information from the client request.

• The request itself comprises:


• a request line- specifies the HTTP Method used and Http version
• a set of request headers, and
• body section-message or data which is being send to the server

• When a request is submitted from a Web page, it is almost always a


GET or a POST method.

• It specifies the manner that the servlet expects to receive from the web
server the collection of data submitted by the user
12

HTTP Methods: GET method


• Contacts server and sends data in single step

• It is used when the amount of form data is small

• Appends data to action URL separated by question mark in the form


• URL?name=value&name=value& name=value

• Common uses of get requests are to retrieve an HTML document or


an image
13

HTTP Methods :POST method


• Here data sent in two steps
• Browser contacts server
• Sends data

• The amount of form data is large

• A POST request supplies parameters in the same syntax, only it is in


the “body” section of the request and is therefore harder for the user to
see

• Common uses of post requests are to send the to Web-server,


information from an HTML form in which the client enters data
14

HTTP Response
After receiving and interpreting a http request message, a server
responds with an HTTP response message

The server sends a response that comprises:


• a status line- status code that gives the result of the request
and version of HTTP
• a set of response headers and
• body section-requested resource is returned to the client
15

The Servlet Architecture


• The heart of servlet architecture is the interface
javax.servlet.Servlet

• The Servlet interface defines methods that manage servlets and


their communication with clients

• Defines five basic methods:


• init()
• service()
• destroy()
• getServletConfig()
• getServletInfo()
16

Servlet Architecture
• A servlet is any class that either implement the Servlet interface or
extend a class that implements the Servlet interface

• Most user-written servlet classes are extensions to HttpServlet

• The HttpServlet class is an extension of GenericServlet which


implements Servlet Interface and it includes methods for handling
HTTP-specific data.

• It provides a number of methods ,such as doGet(), doPost(), and


doPut(), to handle particular types of HTTP requests (GET, POST, and
so on).
17

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()
...()

should not be called by doGet()


doDelete()
your code
doPost() doPut()

You can provide an implementation of


these methods in HttpServlet descendent
classes
19

The init() Method


• The init method is called by web container when the servlet is
first created; it is not called again for each user request.

• The servlet is normally created when a user first invokes a URL


corresponding to the servlet

public void init( ServletConfig config)


throws ServletException {
// Initialization code...
}
• This method allows a servlet to perform any initialization
required before being invoked against an http request
20

The service() Method


• Every call to the servlet creates a new thread that calls the service
method

• The default implementation of the service() method, which figures out


what kind of request is (GET, POST, PUT, DELETE, TRACE,OPTION)
is being made and then invokes and call the appropriate method:
doGet, doPost, doPut, doDelete, doTrace,doOption

• Receives both a ServletRequest object and a ServletResponse


object

• 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

• Usually we do not need to override this method


21

The destroy() Method


• Called by the Web container when the servlet instance is
being eliminated

• The Servlet specification guarantees that all requests will


be completely processed before this method is called

• Override the destroy method when:

• You need to release any servlet-specific resources that you had


opened in the init() method

• You need to persist the state of the servlet


22

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

The HttpServlet class


• To be a Web-based servlet a class should extend HttpServlet
and override doGet or doPost, depending on whether the data
is being sent by GET or by POST.

• Depending on the type of request these methods are called by


the HttpServlet class's service method, which is called
when a request arrives at the server.

• Both doGet and doPost take two argument: HttpServletRequest


object and HttpServletResponse object which enable
interaction between the client and the server
25

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

• The HttpServletResponse methods make it easy to return the


servlet's results in HTML format to the Web client.

• The HttpServletResponse lets you specify outgoing information


such as HTTP status codes (200, 404, etc.) and response headers
(Content-Type, Set-Cookie, etc.)

• 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

• String[] getParameterValues( String name )


Returns a String array containing the values for a specified servlet
parameter.

• 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.

• HttpSession getSession(boolean create)


Returns an HttpSession object associated with the client's
current browsing session.

• An HttpSession object can be created by this method (true


argument) if an HttpSession object does not already exist for
the client.

• HttpSession objects can be used in similar ways to Cookies


for uniquely identifying clients.
30

HttpServletResponse Interface
• In order to do anything useful, a servlet must send a response to each
request that is made to it.

• In an HTTP servlet, the response can include three components:


• a status code, any number of HTTP headers, and a response body.

• HttpServletResponse interface include different methods needed to


create and manipulate a servlet’s output

• Every call to doGet or doPost for an HttpServlet receives an object that


implements interface HttpServletResponse.

• The Web server that executes the servlet creates an


HttpServletResponse object and passes this to the servlet's service
method (which, in turn, passes it to doGet or doPost
31

HttpServletResponse Interface
• Methods
• void addCookie( Cookie cookie ) -Used to add a Cookie to the
header of the response to the client

• Boolean containsHeader(String name)-Checks whether the


response message header has a field with the specified name.

• Void setHeader(String name,String value)


Adds a field to the response header with the given name and value.
32

HttpServletResponse Interface
• PrintWriter getWriter() -Obtains a character-based output stream
enabling text data to be sent to the client

• void setContentType( String type ) =Specifies the MIME type of the


response to the browser. The MIME type helps the browser determine how
to display the data (or possibly what other application to execute to
process the data).

Eg:MIME type "text/html" indicates that the response is an HTML


document, so the browser displays the HTML

• void sendRedirect()-Redirect an HTTP request to another URL


33

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

• The different methods to achieve session tracking are:


• Hidden fields
• URL rewriting
• Cookies
• Session tracking API
Session Tracking:Cookies
• Cookies are the mostly used technology for session tracking.

• Cookie is a key value pair of information, sent by the server to the


browser which should be saved by the browser in its space in the
client computer

• The cookie is sent as a request header line in each subsequent


request sent by the browser to the web server

• Once a browser session ends, browser loses the contents of a


session cookie.
41

Session Tracking:Cookies
• A web browser, is expected to support twenty cookies per host, of at
least four kilobytes each

• At the time a cookie is created, it is given a lifetime.

• 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

Java Cookie API


• A Java cookie is an object of the javax.servlet.http.Cookie class.

• Common applications for cookies include storing user preferences,


automating low security user sign-on facilities, and helping collect data
used for "shopping cart" style applications.

Cookies are created with the Cookie constructor


Cookie (String name, String value)

• Cookies are saved one at a time into HTTP response headers, using the
addCookie() method in HttpServletResponse.

• Cookies are passed back from client(browser) to server using HTTP


request headers. They are retrieved at server side using getCookies()
method in HttpServletRequest.
44

Java Cookie API


Methods:
• void setComment(String s)

• void setMaxAge(int s)
• int getMaxAge()

• String getName()

• String getValue()
• void setValue(String s)
45

Java Cookie API-Example


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

public class UseCookies extends HttpServlet


{
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out;
response.setContentType("text/html");
out = response.getWriter();
Cookie cookie = new Cookie("CName","CookieValue");
cookie.setMaxAge(100);
response.addCookie(cookie);
46

Java Cookie API-Example

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:

 looking up the session object associated with the current request


 creating a new session object when necessary
 looking up information associated with a session
 storing information in a session
 and discarding completed or abandoned sessions

• Every request is associated with an HttpSession object

• To get the session object use the method:


HttpServletRequest.getSession()
Creating Session
• Example:
HttpSession session = request.getSession();

• It returns the current HttpSession associated with this request.If no


session still exists, a new one is created and returned

• 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

HttpSession session = request.getSession();


session.setAttribute("name", "Svetlin Nakov");

• Objects in the session can be removed when not needed more

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)

• Extracting existing object:

Integer accessCount =
(Integer) session.getAttribute("accessCount");

• Getting a list of all “keys” associated with the session

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();

• Checking when the session was first created

public long getCreationTime();

• Checking when the session was last active

public long getLastAccessedTime();


52

Session Timeout
• We can get the maximal session validity interval
(in seconds)

public int getMaxInactiveInterval();


• After such interval of inactivity the session is automatically
invalidated

• We can modify the maximal inactivity interval

public void setMaxInactiveInterval (int 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();

• Typically done during the "user logout"

Potrebbero piacerti anche