Contents
1. Java Servlets Technology Overview
u What is a Java Servlet?
u Servlet Services
u Why Use Servlets?
u Time Servlet – Example
u Deploying Servlets on Eclipse IDE
2. Servlets Architecture
u Servlets API
u Servlets Life-Cycle
3. Contents
Servlet (2)
Examples
u Processing Parameters – Hello Servlet
u Image Counter Servlet
4. Using Sessions
u What is a Session?
u The Sessions API
u Session Timeout
5. Session Examples
u Login / Logout Application
u The Browser's Cache Problems
Java Servlets
Technology Overview
What is a Java Servlet?
u Java Servlets are:
u Technology for generating dynamic Web pages (like
PHP, ASP, ASP.NET, ...)
u Protocol and platform-independent server side
components, written in Java, which extend the
standard Web servers
u Java programs that serve HTTP requests
u The HttpServlet class
u Provides dynamic Web content generation (HTML, XML,
…)
What is a Java Servlet? (2)
u Servlets
u Provide a general framework for services built on the request-
response paradigm
u Portable to any Java application server
u Have access to the entire family of Java and Java EE APIs
u JDBC, Persistence, EJB, JMS, JAX-
WS, JTA, JTS, RMI, JNDI, JAXP, ...
u Fundamental part of all Java
Web application technologies
(JSP, JSF, ...)
Servlet Services
u Java Servlets provide many useful services
u Provides low-level API for building Internet
services
u Serves as foundation to JavaServer Pages
(JSP) and JavaServer Faces (JSF)
technologies
u Can deliver multiple types of data to any
client
u XML, HTML, WML, GIF, etc...
u Can serve as “Controller” of JSP/Servlet
application
u
Why Use Servlets?
Portability
u Write once, serve everywhere
u Power
u Can take advantage of all Java APIs
u Elegance
u Simplicity due to abstraction
u Efficiency & Endurance
u Highly scalable
Why
u Safety
Use Servlets? (2)
u Strong type-checking
u Memory management
u Integration
u Servlets tightly coupled with server
u Extensibility & Flexibility
u Servletsdesigned to be easily extensible, though
currently optimized for HTTP uses
u Flexible invocation of servlet (SSI, servlet-chaining,
filters, etc.)
Time Servlet – Example
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class TimeServlet extends HttpServlet {
public void doGet(HttpServletRequest aRequest,
HttpServletResponse aResponse)
throws ServletException, IOException {
PrintWriter out = aResponse.getWriter();
out.println("<HTML>");
out.println("The time is: " +
new java.util.Date());
out.println("</HTML>");
}
}
Deploying Servlets on Eclipse
IDE
u First create new Web application
Deploying Servlets on Eclipse
IDE (2)
u Add new servlet to the Web
application
Deploying Servlets on Eclipse
IDE (3)
u Run the servlet
Deploying Servlets on Eclipse
IDE (4)
u The servlet in action
Java Servlets
Technical Architecture
Servlets Architecture
u The HttpServlet class
u Serves client's HTTP requests
u For each of the HTTP methods, GET, POST, and
others, there is corresponding method:
u doGet(…) – serves HTTP GET requests
u doPost(…) – serves HTTP POST requests
u doPut(…), doHead(…), doDelete(…),
doTrace(…), doOptions(…)
u The Servlet usually must implement one of the
first two methods or the service(…) method
Servlets Architecture (2)
u The HttpServletRequest object
u Contains the request data from the client
u HTTP request headers
u Form data and query parameters
u Other client data (cookies, path, etc.)
u The HttpServletResponse object
u Encapsulates data sent back to client
u HTTP response headers (content type, cookies,
etc.)
u Response body (as OutputStream)
u Servlets
The Architecture
HTTP GET (3)when:
method is used
u The processing of the request does not change the
state of the server
u The amount of form data is small
u You want to allow the request to be bookmarked
u The HTTP POST method is used when:
u The processing of the request changes the state of
the server, e.g. storing data in a DB
u The amount of form data is large
u The contents of the data should not be visible in the
URL (for example, passwords)
Servlets API
u The most important servlet functionality:
HttpServletRequest.getParameter(String)
u Retrieve the HTML form parameters from the
request (both GET and POST parameters)
u Retrieve a servlet initialization parameter
ServletConfig.getInitParameter()
u Retrieve HTTP request header information
HttpServletRequest.getHeader(String)
uServlets APIresponse
Set an HTTP (2) header / content type
HttpServletResponse.setHeader(<name>, <value>) /
HttpServletResponse.setContentType(String)
u Acquire a text stream for the response
HttpServletResponse.getWriter()
u Acquire a binary stream for the response
HttpServletResponse.getOutputStream()
u Redirect an HTTP request to another URL
HttpServletResponse.sendRedirect()
Servlets Life-Cycle
• The Web container New Destroyed
manages the life
cycle of servlet init()
Running
destroy()
instances
• The life-cycle service()
...()
methods should not doGet()
be called by your doDelete()
code doPost() doPut()
u You can provide an implementation of these
methods in HttpServlet descendent classes to
manipulate the servlet instance and the resources
it depends on
The init() Method
u Called by the Web container when the
servlet instance is first created
u The Servlets specification guarantees that
no requests will be processed by this
servlet until the init method has completed
u Override the init() method when:
u You need to create or open any servlet-
specific resources that you need for
processing user requests
u You need to initialize the state of the servlet
The service() Method
u Called by the Web container to process a user
request
u Dispatches the HTTP requests to doGet(…),
doPost(…), etc. depending on the HTTP request
method (GET, POST, and so on)
u Sends the result as HTTP response
u Usually we do not need to override this method
The destroy() Method
u Called by the Web container when the servlet
instance is being eliminated
u The Servlet specification guarantees that all requests
will be completely processed before this method is
called
u Override the destroy method when:
u You need to release any servlet-specific resources that
you had opened in the init() method
u You need to persist the state of the servlet
Java Servlets
Examples
Processing Parameters –
Hello Servlet
u We want to create a servlet that
takes an user name as a parameter
and
<form says "Hello,
method="GET <user_name>"
or POST" action="the servlet">
<input type="text" name="user_name">
u We need HTML form with a text field
</form>
u The servlet can later retrieve the
String name = request.getParameter("user_name");
value entered in the form field
Hello Servlet – 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>
HelloServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloServlet extends HttpServlet {
Hello Servlet – Example
HelloServlet.java
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
ServletOutputStream out = response.getOutputStream();
String userName = request.getParameter("user_name");
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>");
}
Creating The Form in Eclipse
IDE
u Create new HTML form
Creating New Servlet in
Eclipse IDE
u Create new Servlet
Hello Servlet in Action
Hello Servlet –
u What
HTTPhappens
Requestwhen the user enters his name?
u InternetExplorer (IE) sends the following HTTP
request to Tomcat
GET /FirstWebApp/HelloServlet?user_name=Nakov HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg,image/pjpeg,
application/vnd.ms-excel, application/vnd.ms-powerpoint,
application/msword, application/x-shockwave-flash, */*
Accept-Language: bg
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT
5.1; Q312461)
Host: nakov:8084
Connection: Keep-Alive
Hello Servlet –
u What
HTTPhappens when Tomcat receive and
Response
process the HTTP request
u Tomcat sends the following HTTP response to
Internet Explorer
HTTP/1.1 200 OK
Content-Length: 100
Date: Fri, 26 Mar 2006 10:06:28 GMT
Server: Apache-Coyote/1.1
<html><head>
<title>Hello Servlet</title>
</head><body>
<h1>Hello, Nakov</h1>
</body></html>
Image Counter Servlet
u We want to create a servlet that displays
an image counter (as JPEG image)
u The servlet should maintain an internal
counter
u Can be initialized in the init() method
and incremented in the doGet() method
u It should produce binary output (the JPEG)
image
u The content type should be set to
"image/jpeg"
Image Counter
import javax.servlet.*;
Servlet (2)
import javax.servlet.http.*;
...
public class ImageCounterServlet extends HttpServlet {
private String mStartDate;
private int mVisitCounter;
public void init() {
mStartDate = (new Date()).toString();
mVisitCounter = 0;
}
public BufferedImage createImage(String msg) {
...
}
Image Counter Servlet (3)
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
String msg;
synchronized(this) {
mVisitCounter++;
msg = "" + mVisitCounter + " visits since " +
mStartDate;
}
BufferedImage image = createImage(msg);
response.setContentType("image/jpeg");
OutputStream out = response.getOutputStream();
// Encode the image in JPEG format and
// write the image to the output stream
}
}
Image Counter Servlet in
Action
Using Sessions
What is a Session?
u A session is a state associated with particular
user that is maintained at the server side
u Sessions persist between the HTTP requests
u Sessions enable creating applications that
depend on individual user data. For example:
u Login / logout functionality
u Wizard pages
u Shopping carts
u Personalization services
u Maintaining state about the user’s preferences
Sessions in Servlets
u Servlets include a built-in Sessions API
u Sessions are maintained automatically, with
no additional coding
u The Web container associates an unique
HttpSession object to each different client
u Different clients have different session
objects at the server
u Requests from the same client have the
same session object
u Sessions can store various data
The Sessions API
u The sessions API allows
u To get the HttpSession object from the
HTTPServletRequest object
u Extract data from the user’s session object
u Append data to the user’s session object
u Extract meta-information about the session object, e.g.
when was the session created
Getting The Session Object
u To get the session object use the method
HttpSession session = request.getSession();
HttpServletRequest.getSession()
u Example:
u If the user already has a session, the
existing session is returned
u If no session still exists, a new one is created
and returned
u If you want to know if this is a new session,
call the isNew() method
Behind The Scenes
u When you call getSession() each user is
automatically assigned a unique Session ID
u How does this Session ID get to the user?
u Option 1: If the browser supports cookies,
the servlet will automatically create a
session cookie, and store the session ID
within the cookie
u In Tomcat, the cookie is called JSESSIONID
u Option 2: If the browser does not support
cookies, the servlet will try to extract the
session ID from the URL
Extracting Data From The
Session
u The session object works like a HashMap
uEnables storing any type of Java object
u Objects
Integer are stored
accessCount = by key (like in hash
tables) session.getAttribute("accessCount");
(Integer)
u Extracting existing object:
u Getting a list of all “keys” associated
Enumeration attributes =
with the session
request.getAttributeNames();
Storing Data In The Session
HttpSession session = request.getSession();
We can store data in the session
session.setAttribute("name", "Svetlin Nakov");
u
object for using it later
session.removeAttribute("name");
u Objects in the session can be
removed when not needed more
Getting Additional Session
Information
public String getId();
u Getting the unique session ID associated
with this user, e.g. gj9xswvw9p
public boolean isNew();
u Checking if the session was just created
u Checking
public when the session was first
long getCreationTime();
created
u Checking
public when the session was last active
long getLastAccessedTime();
Session Timeout
public int getMaxInactiveInterval();
u We can get the maximal session validity
interval
(in seconds)
u After such interval of inactivity the session is
automatically invalidated
u We void
public can modify the maximal inactivity
setMaxInactiveInterval interval
(int seconds);
u A negative value specifies that the session
should never time out
Terminating Sessions
public void invalidate();
u To terminate session manually use the method:
u Typically done during the "user logout"
u The session can become invalid not only manually
u Sessions can expire automatically due to inactivity
Login / Logout – Example
u We want to create a simple Web application
that restricts the access by login form
u We will use sessions to store information about
the authenticated users
u We will use the key "username"
u When it present, there is a logged in user
u During the login we will add the user name in the
session
u Logout will invalidate the session
u The main servlet will check the current user
Login Form
LoginForm.html
<html>
<head><title>Login</title></head>
<body>
<form method="POST" action="LoginServlet">
Please login:<br>
Username:
<input type="text" name="username"><br>
Password:
<input type="password" name="password"><br>
<input type="submit" value="Login">
</form>
</body>
</html>
Login Servlet
LoginServlet.java
public class LoginServlet extends HttpServlet {
public void doPost(HttpServletRequest req,
HttpServletResponse resp)
throws IOException, ServletException {
String username = req.getParameter("username");
String password = req.getParameter("password");
PrintWriter out = resp.getWriter();
if (isLoginValid(username, password)) {
HttpSession session = req.getSession();
session.setAttribute("USER", username);
response.sendRedirect("MainServlet");
} else {
response.sendRedirect("InvalidLogin.html");
}
}
}
Main Servlet
MainServlet.java
public class MainServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse resp)
throws ServletException, IOException {
HttpSession session = request.getSession();
String userName = (String)
session.getAttribute("USER");
if (userName != null) {
response.setContentType("text/html");
ServletOutputStream out = resp.getOutputStream();
out.println("<html><body><h1>");
out.println("Hello, " + userName + "! ");
out.println("</h1></body></html>");
} else {
response.sendRedirect("LoginForm.html");
}
}
}
Logout Servlet
LogoutServlet.java
public class LogoutServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
session.invalidate();
response.setContentType("text/html");
ServletOutputStream out =
response.getOutputStream();
out.println("<html><head>");
out.println("<title>Logout</title></head>");
out.println("<body>");
out.println("<h1>Logout successfull.</h1>");
out.println("</body></html>");
}
}
Invalid Login Page
InvalidLogin.html
<html>
<head>
<title>Error</title>
</head>
<body>
<h1>Invalid login!</h1>
Please <a href="LoginForm.html">try again</a>.
</body>
</html>
The Browser's Cache
Problems
u Most Web browsers use caching of the displayed
pages and images
u This can cause the user to see old state of the pages
u Seems like a bug in the application
u To prevent showing the old state we need to
disable the browser cache:
response.setHeader("Pragma", "No-cache");
response.setDateHeader("Expires", 0);
response.setHeader("Cache-Control", "no-cache");
1. Problems
Create a servlet that prints in a table the
numbers from 1 to 1000 and their square root.
2. Create a servlet that takes as parameters two
integer numbers and calculates their sum.
Create a HTML form that invokes the servlet. Try
to use GET and POST methods.
3. Implement a servlet that plays the "Number
guess game". When the client first invoke the
servlet it generates a random number in the
range [1..100]. The user is asked to guess this
number. At each guess the servlet says only
"greater" or "smaller". The game ends when the
user tell the number.
1. Homework
Create a servlet that takes as a parameter a
number and displays it as image that is hard to
be recognized by OCR software. The image
should have intentionally inserted defects.
2. Create an HTML form and a servlet for
performing conversions of distances from one
metric to another. The metrics that should be
supported are: meter, centimeter, kilometer,
foot, inch, yard, mile.
1 cm = 0.01 meters 1 km = 1000 meters
1 foot = 0.3048 meters 1 inch = 0.0254 meters
1 yard = 0.9144 meters 1 mile = 1609.344 meters
3. Homework
Create (2) of HTML forms and servlets
a sequence
that allow entering information about a student.
The information is entered in 3 steps in 3 separate
forms:
Step 1: First name, last name, age
Step 2: Address (country, town, street)
Step 3: University, faculty, specialty
The data entered in the 3 steps should be stored
in the session and finally displayed.
4. Create a servlet that reads an image (from WEB-
INF\img\logo.gif) and returns it.