Servlets

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 81

JAVA SERVLETS

● Servlets are the Java programs that run on the Java-enabled web server or
application server. They are used to handle the request obtained from the web
server, process the request, produce the response, then send a response back to
the web server.
● Servlets can be thought of as providing a way to extend the capabilities of a web
server so that the server is tailored to provide certain services to web users.
● Servlets work on the server-side.
● Servlets are capable of handling complex requests obtained from the web server.
STEPS INVOLVED IN EXECUTION OF
SERVLETS

● The clients send the request to the web server.


● The web server receives the request.
● The web server passes the request to the corresponding servlet.
● The servlet processes the request and generates the response in the form of
output.
● The servlet sends the response back to the web server.
● The web server sends the response back to the client and the client browser
displays it on the screen.
SERVLET ARCHITECTURE
1. Client
The client shown in the architecture above is primarily working as a medium who is
sending out HTTP requests over to the web server and again processing the response it
gets back from the server. As we can see in the diagram, our client here is the web
browser.
2. Web Server
Primary job of a web server is to process the requests and responses that a user sends
over time and maintain how a web user would be able to access the files that has been
hosted over the server. The server we are talking about here is a software which
manages access to a centralized resource or service in a network.. There are precisely
two types of web servers:
● Static web server
● Dynamic web server
3. Web Container
Web container is another typical component in servlet
architecture which is responsible for communicating
with the servlets. Two prime tasks of a web container
are:
● Managing the servlet lifecycle
● URL mapping
Every servlet should override the following 3 methods
namely:
● init()
● service()
● destroy()
OPERATING SERVLET REQUEST
● When an HTTP request message is received by a servlet-capable server, it first
determines—based on the URL of the request—that the request should be
handled by a servlet. For example, a server might be configured to treat any
request to any URL for which the path component begins with servlet as a request
that should be handled by a servlet.
● The server next determines from the URL which servlet should handle the request
and calls a method on that servlet. Two parameters are passed to the method: an
object implementing the HttpServletRequest interface, and an object
implementing the HttpServletResponse interface.
● Both of these interfaces are defined as part of the Java Servlet API, which is
implemented by the server. The first object provides methods that can be used by
the servlet to access the information contained in the HTTP request message
received by the server. The second object can be used to record information that
the servlet wishes to include in the HTTP response message that the server will
send to the client in reply to the request.
● The servlet method executes, typically calling methods on the HttpServletRequest
and HttpServletResponse objects passed to it. The information stored in the latter
object by the servlet method typically includes an entire HTML document along
with some HTTP header information, such as the document Content-Type. When
the servlet method has finished its processing, it returns control to the server.
● The server formats the information stored in the HttpServletResponse object by
the servlet into an HTTP response message, which it then sends to the client that
initiated the HTTP request.
DYNAMIC WEB PAGES
▪ Dynamic web pages are server-side web pages, each time it is viewed,
we see different content.
▪ It is controlled by Application server processing server-side scripts.
▪ The dynamic web pages can also change their contents on the
request of the client. They have the capability to generate new
content according to time and need.
▪ The main difference between static and dynamic web pages is that
static web page remains the same for all clients or users while
dynamic web page changes itself according to the time and as per the
user’s request.
8
● A Servlet is a Java class instantiated by the server to
produce a dynamic response.
● Web server response can be Static or Dynamic:
1.STATIC – When a browser has requested an
HTML document. It just finds and sends the content.
2.DYNAMIC – HTML document is generated by a
program in response to a HTTP request. Example, Visiting a
search engine website.
EXAMPLE PROGRAM - DYNAMIC
• A counter variable called ‘visits’
will be incremented holding the
value output as a part of the HTML
document produced by the servlet.
OUTPUT:

Here,
The program prints Hello World! and
the number of times the servlet has
been visited since the servlet started.
The page is no longer Static but
Dynamic.
POTENTIAL PROBLEMS

1. Assuming one instance of servlet on one server, but


• Many web sites are distributed over multiple servers
• Even a single server can create multiple instances of a single servlet
• If multiple users access this servlet at nearly the same time, the
multiple execution of doGet() causes different users to see the same
visit count.
2. Even if the assumption is correct, this servlet does not handle
concurrent accesses properly.

13
Servlet Life Cycle Methods

The class Servlet provides the methods to control and supervise the life
cycle of servlet. There are three life cycle methods of a Servlet :
• init()
• service()
• destroy()
METHODS
init() method
• A servlet’s life begins here .
• This method is called only once to load the servlet . Since it is called only once in
it’s lifetime , therefore “connected architecture” code is written inside it because
we only want once to get connected with the database.
• This method receives only one parameter, (i.e)ServletConfig object.
• This method has the possibility to throw the ServletException.
• Once the servlet is initialized, it is ready to handle the client request.
• The Prototype for this method:
public void init (ServletConfig con) throws ServletException { }
service() method
• The service() method is the most important method to perform that provides the connection
between client and server.
• The web server calls the service() method to handle requests coming from the client( web
browsers) and to send response back to the client.
• This method determines the type of Http request (GET, POST, PUT, DELETE, etc.) .
• This method also calls various other methods such as doGet(), doPost(), doPut(), doDelete(), etc.
as required.
• This method accepts two parameters.
• The Prototype for this method:
public void service(ServletRequest req,ServletResponse resp)
throws ServletException ,IOException { }
destroy() method

• The destroy() method is called only once.


• It is called at the end of the life cycle of the servlet.
• This method performs various tasks such as closing connection with
the database, releasing memory allocated to the servlet, releasing
resources that are allocated to the servlet and other cleanup activities.
• When this method is called, the garbage collector comes into action.
• The Prototype for this method:
public void destroy( )
Example
Index.jsp
<%@ page language="java“ contentType="text/html; charset=ISO-8859-1"pageEncoding="ISO-8859-1"%>
<!DOCTYPE html >
<html>
<head>
<title>Servlet Lifecycle Example</title>
</head>
<body>
<form action="ServletLifecycle" method="post">
<input type="submit" value="Make request" />
</form>
</body>
</html>
ServletLifecycleExample.java

import javax.servlet.ServletResponse;
public class ServletLifecycleExample extends GenericServlet {
public void init() {
// initialize the servlet, and print something in the console.
System.out.println("Servlet Initialized!");
}
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {

// the service method will


response.setContentType("text/html");

PrintWriter out = response.getWriter();


out.println("Servlet called from jsp page!");
}
public void destroy() {
// close connections etc.
}
}
OUTPUT
Parameter data and Query Strings
• consider a URL such as the following:
http://www.example.com/servlet/PrintThis?arg=aString
• within a URL, a question mark (?) marks the end of the path portion
of the URL and the beginning of the query portion of the URL, and
that the query portion of the URL consists of a query string.
• In this case, the query string contains one parameter, named arg,
which is assigned the string value aString.
• All query string parameter values are treated as strings, and that they
should not be quoted
• The following URL’s query string contains two parameters:
http://www.example.com/servlet/PrintThis?arg=aString&color=red
• Order of parameters is not important, so the following URL contains
exactly the same parameter data as the preceding URL, although at a
surface level the two query strings appear to be different:
• http://www.example.com/servlet/PrintThis?color=red&arg=aString
• A parameter name or value can be composed of any sequence of 8-
bit characters, including control characters and other nonprinting
characters.
• However, if a name or value contains any nonalphanumeric
characters, then the name or value will undergo a transformation
known as URL encoding before being included in the query string.
• It should be clear that the URL encoding transformation can be
reversed, giving back the original unencoded string. The reverse
transformation is called URL decoding.
URL Encoding Algorithm:
• initialize the result to the empty string
• for each 8-bit character in the original string
• if the character is an alphanumeric
• concatenate the character to the result
• else if the character is a space
• concatenate a plus sign (+) to the result
• else
• concatenate a percent sign (%) followed by the two-digit hexadecimal value of the character
to the result
• endif
• endfor
• return result
Servlets and Parameter Data
• If a query string is included in the URL used to access a servlet, the
servlet can obtain the query string as well as the parameter data
contained in the query string by using the HttpServletRequest
methods:
OUTPUT:
Forms and Parameter Data

username=you&lifestory=less+is+more&boxgroup1=funny
&boxgroup1=smart&doit=Publish+My+Life%27s+Story
• If the method attribute of a form element is assigned the value get, then
the browser will append the query string it constructs to the form’s action
URL and perform an HTTP GET using the resulting URL.
• If the method is set to post, then the same query string will be constructed,
but it will be passed to the server via the body of the HTTP request rather
than as part of the URL.
• POST request can send a query string of essentially any length in the body
of the request, if a form contains a textarea or for some other reason might
generate a particularly long query string, the POST request method should
definitely be used.
• Almost all browsers will display a warning message if a user attempts to
send a POST request more than once.
SESSIONS
• Each HTTP request is examined by the server to see if it contains a special
identifier known as a session ID .
• If a request does not contain a session ID, then the request is assumed to be from
a new user and the web server generates a new unique session ID that is
associated with this user.
• When the HTTP response message is created by the web server, the session ID
will be included as part of the response.
• If the browser receiving this response supports the session convention (details on
this also in the next section), it will store the session ID contained in the response
and send it back to the server as part of subsequent HTTP requests.
• Such a collection of HTTP requests, all associated with a single session ID, is
known as a session.
CREATING A SESSION
• A server complying with the Java servlet API supports the session
concept by associating an HttpSession object with each session
maintained by the server.
• Each object stores the session ID for its session as well as other
session-related information.
• An HttpSession object is created by the server when a servlet calls the
getSession() method on its HttpServletRequest parameter and the
associated HTTP request does not contain a valid session ID; the
getSession() method returns the newly created object.
• On the other hand, if the HTTP request contains a valid session ID,
then a call to getSession() returns the previously created HttpSession
object containing this session ID.
• The servlet can determine whether the HttpSession object returned
by getSession() has been newly created or not by calling the boolean
method isNew() on the HttpSession object.
STORING AND RETRIEVING ATTRIBUTES
• The servlet is implemented by storing and retrieving an attribute
value in the HttpSession object for the user.
• A session attribute is simply a name-value pair that is stored in the
HttpSession object.
• Two methods of HttpSession are used to store and retrieve attributes:
• setAttribute(String name, Object obj) to create or overwrite an
attribute having the given name with the given Object value;
• getAttribute(String name), which returns the value (of type Object)
for the attribute with the given name, or null if there is no attribute
with this name in the HttpSession object.
TERMINATING A SESSION
• The HttpSession interface defines a setMaxInactiveInterval(int interval) method
that takes an integer argument interval representing a number of seconds. If
more than interval seconds elapse between any two HTTP requests to the servlet
from the user represented by this HttpSession object, then the user’s session will
expire before the second of these two requests can be processed.
• More precisely, the web server effectively sets a timer of duration interval for the
session after each HTTP request containing this session’s ID is received.
• If the timer completes before the next request containing this session ID is
received, then the server calls the invalidate() method on the session object,
terminating it.
• Servlet code can also call the invalidate() method directly at any time in order to
terminate a running session.
Some points to be remembered:
• if setMaxInactiveInterval() is called with a
negative argument, then the session will not
expire, although it could still be terminated by a
call to invalidate().
• Second, if setMaxInactiveInterval() is not called
explicitly for a session object, then the server
will determine the default expiration behavior of
the object; a common default is for a server to
expire sessions after 20 minutes or so.
• Finally, server restart will typically invalidate all
sessions managed by the server, although some
servers may support persistent sessions that
survive server restarts.
COOKIES

• A cookie is a name-value pair that a web server sends to a client


machine as part of an HTTP response, specifically through the Set-
Cookie header field. Browsers will typically store the cookie pairs
found in the response in a file on the client machine.
• The cookie mechanism is a natural means of implementing the session
concept automatically as part of the processing performed by the
getSession() method.
• Specifically, if a server uses cookies to maintain a session, then a call to
getSession() will cause the server to look for a cookie named
JSESSIONID in the Cookie header field of the request.
• A JSESSIONID cookie having the session ID of this new object as
its value is then created, and this cookie is added to the Set-
Cookie header field of the HTTP response (or more precisely, the
cookie is stored on the server and will be sent in the Set-Cookie
header field when the servlet sends its HTTP response). The new
session object is then returned to the servlet.
• Servlets can also explicitly create and use cookies. The Java
servlet API provides a class called Cookie for this purpose. Each
instance of this class corresponds to a single cookie.
• This class can be used to create internal representations of new
cookies and to access the name-value data in existing Cookie
objects.
Key Cookie Class Methods

METHOD PURPOSE
Cookie(String name, String value) Constructor to create a cookie with given name
and value.
String getName() Return name of this cookie
String getValue() Return value of this cookie
void setMaxAge(int seconds) Set delay until cookie expires. Positive value is
delay in seconds, negative value means that the
cookie expires when the browser closes, and 0
means delete the cookie
PORTIONS OF doget() METHOD:
private static final int oneYear = 60*60*24*365;
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Get count from cookie if available, otherwise
// use initial value.
int count = 0;
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (int i=0; (i<cookies.length) && (count==0); i++ {
if (cookies[i].getName().equals("COUNT")) {
count = Integer.parseInt(cookies[i].getValue());
} } }
// Increment the count and add request to client to store it
// for one year.
count++;
Cookie cookie = new Cookie("COUNT", new Integer(count).toString());
cookie.setMaxAge(oneYear);
response.addCookie(cookie);
// Set the HTTP content type in response header
response.setContentType("text/html; charset=\"UTF-8\"");
. . .
“ <body> \n”+
“ <p> you have visited this page “ +count +” time(s) \n: +
“ in the past year, or since clearing your cookies.</p> \n” +
“ </body> \n” +
. . .
The cookie specification calls for the browser to accept at least 20 cookies, or possibly fewer if
the cookies require a significant amount of storage. So, just as with edible cookies, don’t
overdo it.
Another thing to notice in the code is that I have used uppercase alphanumerics for the
cookie name (COUNT). For maximum compatibility with various browsers, following this
practice is advisable, although not strictly required. Also, because cookie values are strings,

(Output of CookieCounter.java after six visits to the servlet’s URL)


I have had to use the Integer class to perform conversions between the integer value that I need in order to perform
increment operations and the String value that is stored in the cookie. The code shown here illustrates a standard
technique for performing these types of conversions by using the parseInt() and toString() methods of Integer.
URL REWRITING
● An alternative to passing a session ID between server and client through HTTP
headers is to pass it via the HTML documents themselves. That is, an alternative is
for the server to write the session ID within every HTML document it returns to
the client in such a way that the URLs that the client subsequently requests will
contain the session ID.
● The server accomplishes this by adding the session ID to every servlet URL
appearing in any page sent to the client. This typically involves rewriting every URL
referencing the servlet in the href attribute of any anchor and the action attribute
of any form output by the servlet
● The HttpServletResponse interface supports this approach to maintaining session
by defining an encodeURL(String url) method.
● Given a url argument, this method returns the same URL plus, if appropriate, a
session ID (when it is “appropriate” to add a session ID is explained later in this
section). The session ID is added via a little-used URL feature known as a path
parameter.
● For example, if the url argument’s value is, say, URLEncodedGreeting (a String
representing a relative URL), and it is appropriate to add a session ID to this URL,
then encodeURL(url) will return something like
URLEncodedGreeting;jsessionid=0157B9E85127D047E2BD464ECE116701
● The server checks for the presence of session information within the request URL
when getSession() is called. In particular, when getSession() is called, it will first
search for a JSESSIONID cookie in the header of the HTTP request.
● If found, then the server will record that cookie processing can be used to
maintain this session and proceed with its session object processing as described
in the previous section. If a JSESSIONID cookie is not found, the server will check
for a jsessionid path parameter in the request URL.
● Typically, the mechanism used by the server to maintain session is transparent to
the servlet code, but if desired the boolean HttpServletRequest methods
isRequestedSessionIdFromCookie() and isRequestedSessionIdFromURL() can be
called by the servlet code to determine how the session ID was transmitted in the
current HTTP request.
● For example,
printSignInForm(servletOut, "Greeting");
we will now have
printSignInForm(servletOut,
response.encodeURL("URLEncodedGreeting"));
and other method calls containing “Greeting” are similarly changed.
● Note that if URL rewriting is to be used to maintain session, it’s important that
every URL referencing the servlet be rewritten. Otherwise, if cookies are
disallowed and the user requests a servlet URL that has not been rewritten, then
no session ID will be transmitted to the servlet in the request.
OTHER CAPABILITIES

Additional HttpServletRequest Methods:


Several methods in HttpServletRequest that return information
that is part of the HTTP request received from the client. This method
printInfo() how these methods can be used to produce output.
Additional HttpServletResponse Methods
In several methods that can be called on the HttpServletResponse
parameter(response object) in order to control various aspects of the HTTP
response generated.
Some methods that must be called before the first buffer flush include
setHeader(), setHeader(), setDateHeader(), setContentLength() has the more
stringent requirement that it must be called before any data is written to be
buffer.
Support for the other HTTP Methods
In addition to doGet() and doPost(), there are other methods defined by
HttpServlet corresponding to HTTP
.doDelete()
.doHead()
.doOptions()
.doPut()
.doTrace()
Java Servlets and Databases

• Servlets are mainly used in Dynamic web


applications which provides dynamic
responses to client requests.
• Dynamic web applications access a database
to provide the client requested data.
• JDBC (Java Database Connectivity) provides
functions to access the Database system.
• Servlets enables Java for CGI programs.
STEPS FOR JDBC CONNECTION IN SERVLETS
Install JDBC Driver:
Install the appropriate JDBC driver in our program to connect with the database. After
installation, place your jar file under “WebContent -> WEB-INF -> lib”.

Import JDBC packages:


To access and process the Database operations, we need to import all the required
“java.sql” packages in the program.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
Register the JDBC Driver:
Registering the driver tells the JVM to load the driver’s class file into the
memory so that we can implement the JDBC operations. Register the driver by
using “Class.forName()” method.
try {
// Register PostgreSQL Driver
Class.forName("org.postgresql.Driver");
}
catch (ClassNotFoundException e) {
System.out.println("Unable to load Driver class");
// e.printStackTrace(); OR you
// can directly print the stack trace
System.exit(1);
}
Establish the Connection to Database:
Establish the connection to the database using the
“DriverManager.getConnection()” method.
String URL = "jdbc:postgresql://localhost/postgres";
String USER = "username";
String PASSWORD = "password";
Connection conn = DriverManager.getConnection(URL, USER,
PASSWORD);

Create a JDBC Statement object:


After successful connection, prepare JDBC statement object using the
Connection object.
Statement stmt = conn.createStatement();
Execute the SQL query:
Construct the SQL query based on the client request and execute the
query using statement object.
stmt.executeQuery(sql);

Close Database connection:


After processing the required operations, finally, close all the database
connection objects.
stmt.close();
conn.close();
EXAMPLE PROGRAM
• home.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Home Page</title>
</head>
<body>

<form action="fetch" method="get">

Fetch Mobile phone details:<input type="submit" value="Search" />

</form>

</body>
</html>
• FetchServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/fetch")
public class FetchServlet extends HttpServlet {

private static final long serialVersionUID = 1L;


final String URL = "jdbc:postgresql://localhost/postgres";
final String USER = "root";
final String PASSWORD = "root";
final String DRIVER = "org.postgresql.Driver";
Connection conn = null;

public void init() throws ServletException {


// Database connection through Driver Manager
try {
Class.forName(DRIVER);
conn = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

try {

// Set the response content type and


// get the PrintWriter object.
response.setContentType("text/html");
PrintWriter out = response.getWriter();

// Set up HTML table formatting for the output


out.println("<html><body>");
out.println("<h3>Mobile Phone Details</h3>");
out.println("<table border=1><tr>" + "<td><b>S.No</b></td>" +
"<td><b>Brand</b></td>"
+ "<td><b>Processor</b></td>" + "<td><b>Operating System</b></td>"
+ "<td><b>Screen Size(inches)</b></td>" +
"<td><b>Battery Life(mAh)</b></td></tr>");

// Create JDBC statement object, construct


// the SQL query and execute the query.
Statement stmt = conn.createStatement();
String sql = "select * from public.mobilePhones;";
ResultSet rs = stmt.executeQuery(sql);

// Loop through the result set to


// retrieve the individual data items.
out.println("</table></body></html>");

// Close Result set, Statement


// and PrintWriter objects.
rs.close();
stmt.close();
out.close();

} catch (SQLException e) {
e.printStackTrace();
}

}
public void destroy() {

// Close connection object.


try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

}
OUTPUT:
Data Storage
Servlets and Concurrency

Suppriya K - 2019239024
M.Sc CS
Data Storage
● Almost all web applications(servlets or related dynamic web
server software) store and retrieve data.
–Typical web app uses a database management system (DBMS)
–Another option is to use the file system
–Proper choice of a data storage mechanism and efficient
implementation of software interacting with this mechanism is
often crucial to developing a responsive and reliable web
application.

● One common web application problem: concurrency


Servlets and Concurrency
● Concurrency means multiple computations are happening at
the same time.
● Ex: Web browser loading several images at the same time, or
web browser can respond to your mouse clicks while it is still
downloading information from a web server are examples of
concurrent processing in action on the client side.
● On a server side, multiple requests to the same servlet may be
executed at the same time. So concurrency container or web
server is multithreaded.
Concurrency

Without concurrent
processing, the second user’s
HTTP request could not begin
to be processed until the first
user’s request was completed,
and the CPU might sit
virtually idle while waiting for
the input/output operation of
the first servlet to complete.
Threads
A thread is a single
execution process. It is a
basic unit of CPU
utilization, consisting of own
program counter, a stack,
and a set of registers.

A program is multithreaded
when multiple threads
execute a single instance of
a program.
Threads
● Tomcat creates a separate thread for each HTTP request
● JVM maintains a data structure containing information about
each of the threads that it is managing.
● Java thread state saved:
–Which statement to be executed next
–The call stack : statement to be executed when the current
method returns plus parameter values for each method.
–The values of local variables for all methods are in the call
stack
Threads
Some examples of values that are not saved when a thread is
suspended:
–Values of instance variables(variables declared outside of
methods)
–Values of class variables(variables declared as static outside
of methods)
–Contents of files, databases and other external resources to
the JVM
Threading Issues
Two threads running in
HelloCounter concurrently.
The initial value of visits is
assumed to be 17.
Thread Synchronization

Java support thread synchronization a lock mechanism in order to


force threads to access shared data in a way that guarantees the
behaviors we want.
–Only one synchronized method within a class can be called at
any one time
Thread
Synchronization

Two servlets invoking a


synchronized method
Servlet Synchronization
● A servlet must be capable of serving more than one client at a
time.
● If several clients issue requests at the same time, methods will
serve each client in a different thread.
● service( ),doGet( ), and doPost( ) can handle many concurrent
clients. It uses lock mechanism to synchronize the threads.
Thank You

You might also like