-
8/6/2019 Building Web Applications Using Servlets_java30
1/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 1
Building WebApplications Using
Servlets Technology
JavaTM Education & Technology Services
-
8/6/2019 Building Web Applications Using Servlets_java30
2/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 2
Table of Contents
Chapter 1: Web/HTTP Overview Chapter 2: Servlets Technology
Chapter 3: How to write servlets code?
Chapter 4: Accessing Databases with JDBC Chapter 5: Getting Familiar with HTTP package
Chapter 6: Session Management
-
8/6/2019 Building Web Applications Using Servlets_java30
3/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 3
Web/HTTP Overview
Chapter 1
-
8/6/2019 Building Web Applications Using Servlets_java30
4/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 4
Overview of HTTP Protocol
Request and Response
System Architectures
Developing Web Applications in Java
Different Web Technologies
Chapter 1 Outline
-
8/6/2019 Building Web Applications Using Servlets_java30
5/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 5
HTTP
What is HTTP?
Hyper Text Transfer Protocol. Stateless Protocol.
Basic Scenario.
HTTP components: HTTP Request.
HTTP Response.
Request or Response consists of three main parts: Response or Request Line.
Header information.
The Body.
-
8/6/2019 Building Web Applications Using Servlets_java30
6/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 6
HTTP
1.Establishes Tcp/Ip connection.
2.Sends Request.
3.Receives Response.
4.Closes connection.
Client
Server
http://163.121.12.2/webindex
Client Browser
Web Server
URL
Protocol Actual Path URI
-
8/6/2019 Building Web Applications Using Servlets_java30
7/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 7
HTTP Request
HTTP Request consists of 3 components:
1.Method-URI-Protocol/Version Methods could be : Get ,Post, Head,Put,Trace, Options
Example: Get /servlet /default.jsp HTTP/1.1
Post / servlet /index.jsp HTTP/1.1
-
8/6/2019 Building Web Applications Using Servlets_java30
8/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 8
HTTP Request contd
2.Request Headers :
Indirectly set by the browser and sent immediately after therequest line. The following are examples of request headers:
Accept: text/plain ;text/html (Note : type/* , */*)
Accept-language: en-ar
Accept-Encoding : gzip
Connection : keep- AliveHost : www.iti.gov.eg or localhost:8080
Referer : http://www.mcit.gov.eg/main.htm
User-agent : Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)
Content-length : 33 (in case of POST)
If-Modified-Since: specified dateIf-Unmodified-Since : Sat, 29 Oct 1994 19:43:31 GMT
Cookie: userID=id456578
-
8/6/2019 Building Web Applications Using Servlets_java30
9/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 9
HTTP Request contd
3. Entity Body (in case of POST method):
UserName=ITI & Password =iti
Note: If the GET method was used:
There will be no entity body. URL in the address bar of the browser will look something like:
www.sitename.com/MyServlet? userName=ITI&password=iti
ITI
***
Sign in
Username
Password
-
8/6/2019 Building Web Applications Using Servlets_java30
10/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 10
HTTP Response
HTTP Response consists of 3 components:
1. Response Line (Protocol/Version Status Code -Description):
Examples:
HTTP/1.1 200 OK
HTTP/1.1 404 error
Status Code Ranges:
100-199 informational, the client must respond with an action
200-299 : request is successful
300-399 : for Redirection , it includes a Locationheaderindicating the new address
400-499 :indicates an error by the client
500-599 : indicates an error by the server
-
8/6/2019 Building Web Applications Using Servlets_java30
11/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 11
HTTP Response (contd)
2.Response HeadersServer: Tomcat/5.5
Date: Mon, 3 Jan 2006 13:13:33 GMT
Content-Type: text/html
Last-Modified: Mon, 11 Jan 2005 13:23:42 GMTContent-Length: 112
Content-Encoding = gzip
-
8/6/2019 Building Web Applications Using Servlets_java30
12/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 12
HTTP Response (contd)
3.Entity Body
HTTP Response Example
Welcome to servlets and jsp course
-
8/6/2019 Building Web Applications Using Servlets_java30
13/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 13
System Architecture
Typically we got 3 logical layers between client browser
and web server :
Presentation
Business logic
The data layer
Handle UI & UserInteraction
Programming logic
Data Base Acess
-
8/6/2019 Building Web Applications Using Servlets_java30
14/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 14
Types of Architecture
Three-Tier Architecture: Presentation layer.
Business logic layer.
Data layer.
Two- Tier Architecture: Fat client (Presentation &
Business logic).
Disadvantages.
-
8/6/2019 Building Web Applications Using Servlets_java30
15/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 15
System Architectures contd
N-Tier Architecture:
Provides more flexibility in modules development. The business logic layer is divided by function instead of being
physically divided. It is divided into:
User interface.
Presentation logic.
Business logic.
Infrastructure services.
Data layer.
-
8/6/2019 Building Web Applications Using Servlets_java30
16/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 16
Developing Web Applications in java
Web Server architecture: Web Server
ASP
Web container
-
8/6/2019 Building Web Applications Using Servlets_java30
17/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 17
Developing Web Applications in java
Application Server
Web Tier
Business
EJB Container
J2EE
DB
Browser
Mobile
Desktop
Legacy
SOAP
HTTP
SOAP
RMI
COBOL
XML
-
8/6/2019 Building Web Applications Using Servlets_java30
18/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 18
Web Technologies
CGI (Common Gateway Interface)
Cold Fusion
Server Side Java Script (SSJS)
PHP
Servlet
JSP
ASP
ASP.NET
-
8/6/2019 Building Web Applications Using Servlets_java30
19/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 19
Servlets Technology
Chapter 2
-
8/6/2019 Building Web Applications Using Servlets_java30
20/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 20
Chapter 2 Outline
Advantages of Servlets
Servlet Container
Servlet Life Cycle
Building and Deploying a Web Application
The Deployment Descriptor
Tomcat Web Server Structure
First Servlet Example
-
8/6/2019 Building Web Applications Using Servlets_java30
21/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 21
What is a Servlet?
Client info (host name,form data)
Success or failure
Process results(access database)
Format results and produceHTML
Send page back to client
Browser Servlet
Request
Response
-
8/6/2019 Building Web Applications Using Servlets_java30
22/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 22
What is a Servlet? (contd)
A Servlet is a Java program that runs on aserver, that produces dynamic pages
typically in response to client requests.
Servlet main jobs: It reads and process implicit and explicit data sent by the
client
Send the implicit / explicit data to the client with a proper
format Its not restricted to HTTP requests
-
8/6/2019 Building Web Applications Using Servlets_java30
23/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 23
Advantages of Servlets
Performance
Portability (supported by many web servers)
Rapid development cycle (rich library , high-level utilities)
Secure
Inexpensive
-
8/6/2019 Building Web Applications Using Servlets_java30
24/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 24
Servlet Container
What is a Servlet container ?
Its actually the interface between the servletclass and the client requests.
Is a container that is responsible for
loading , processing and
unloading the servlets.
Managing servlets.
-
8/6/2019 Building Web Applications Using Servlets_java30
25/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 25
Servlet Container (contd)
Request
Response
Servlet
HTTP
Request
Response
WebServer
Servlet Container
-
8/6/2019 Building Web Applications Using Servlets_java30
26/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 26
Servlet Container contd
Well known servlet containers:
Tomcat JRun
WebSphere
Glassfish
OC4J (Oracle)
StarNine WebStar
-
8/6/2019 Building Web Applications Using Servlets_java30
27/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 27
How Servlets works?
-
8/6/2019 Building Web Applications Using Servlets_java30
28/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 28
Servlets Life Cycle
Load Initialize
init()
Destroydestroy()
Execute
service()
1 2 3
4
-
8/6/2019 Building Web Applications Using Servlets_java30
29/132
JavaTM Education & Technology ServicesCopyright Information Technology Institute 29
Building & Deploying a Web Application
A servlet or JSP application must have a folder named
WEB-INF.
The WEB-INF folder must contain the following: classes folder: it holds the servlets after compilation (i.e. the
.class fileof each servlet), and any helper classes or beans.
lib folder: it holds helper classes that are packaged inside a jarfile.
web.xml file: which is the deployment descriptor of the whole webapplication.
The web application may also contain html pages, jsppages, tld files (tag library descriptors), images or anyother resource files.
-
8/6/2019 Building Web Applications Using Servlets_java30
30/132
JavaTM Education & Technology ServicesCopyright Information Technology Institute 30
What is the deployment descriptor ?
Contains meta-data for a Web Application and
that is used by the container when loading aWeb Application.
It identifies all the elements contained in the webapplication for the servlet container to be able to knowthem
It maps them into URL patterns to be able to callthem as clients
It contains configuration settings specific to thatapplication.
-
8/6/2019 Building Web Applications Using Servlets_java30
31/132
JavaTM Education & Technology ServicesCopyright Information Technology Institute 31
Deployment Descriptor - Example
TestingTestingServlet
Testing/MyURL
index.htmlindex.htmindex.jsp
-
8/6/2019 Building Web Applications Using Servlets_java30
32/132
JavaTM Education & Technology ServicesCopyright Information Technology Institute 32
Tomcat Web Server Structure
-
8/6/2019 Building Web Applications Using Servlets_java30
33/132
JavaTM Education & Technology ServicesCopyright Information Technology Institute 33
First Servlet Example
To develop the first servlet application, you have to go
through the following 6 steps:1. Create the necessary directory structure under tomcats webappsfolder.
2. Write your servlet code (.java).
3. Compile your servlet (produce .class). Remember that we have to
include the servlets and jsp libraries in the class path. This is done bydoing either of the following:
javac -classpath C:\tomcat\common\lib\servlet-api.jar TestingServlet.java
Or permanently referring to the jar files in the classpath environmentvariable of the operating system.
Or put the two jar files in the JDK Installation folder, under ../jre/lib/ext. Or include the two jar files to your project (if you are using an IDE).
-
8/6/2019 Building Web Applications Using Servlets_java30
34/132
JavaTM Education & Technology ServicesCopyright Information Technology Institute 34
First Servlet Example contd
4. Create the deployment descriptor (web.xml) file:
MyServletNamemyPkg.MyServlet
MyServletName /MyServletURL
5. Run Tomcat.
6. Open your browser (e.g. Internet Explorer) and invoke the servletusing its specific URL (http://domain-name/virtual-directory/servlet-url)Example: http://localhost:8080/iti/MyServletURL
http://domain-name/virtual-directory/servlet-urlhttp://domain-name/virtual-directory/servlet-urlhttp://domain-name/virtual-directory/servlet-urlhttp://domain-name/virtual-directory/servlet-urlhttp://domain-name/virtual-directory/servlet-urlhttp://domain-name/virtual-directory/servlet-urlhttp://domain-name/virtual-directory/servlet-urlhttp://domain-name/virtual-directory/servlet-url -
8/6/2019 Building Web Applications Using Servlets_java30
35/132
JavaTM Education & Technology ServicesCopyright Information Technology Institute 35
How to write servlets code?
Chapter 3
-
8/6/2019 Building Web Applications Using Servlets_java30
36/132
JavaTM Education & Technology ServicesCopyright Information Technology Institute 36
Servlets package structure
javax.servlet package
Servlet Interface
ServletConfig Interface
The ServletContext Interface
The ServletRequest Interface
The ServletResponse interface
The GenericServlet Wrapper class
Chapter 3 Outline
-
8/6/2019 Building Web Applications Using Servlets_java30
37/132
JavaTM Education & Technology ServicesCopyright Information Technology Institute 37
Servlet Package Structure
el
http
javax.servlet
JSP
tagext
-
8/6/2019 Building Web Applications Using Servlets_java30
38/132
JavaTM Education & Technology ServicesCopyright Information Technology Institute 38
javax.servlet.*
Some basic interfaces :
Servlet
ServletConfig
ServletContext ServletRequest
ServletResponse
SingleThreadModel
Request Dispatcher
-
8/6/2019 Building Web Applications Using Servlets_java30
39/132
JavaTM Education & Technology ServicesCopyright Information Technology Institute 39
javax.servlet.* (contd)
Some basic classes :
GenericServlet
ServletInputStream
ServletOutputStream The Exception Classes are:
ServletException
UnavailableException
-
8/6/2019 Building Web Applications Using Servlets_java30
40/132
JavaTM Education & Technology ServicesCopyright Information Technology Institute 40
Servlet Interface
Servlet : its the basic interface , any servletmust implements it directly or indirectly
It consists of 5 main methods :
init (ServletConfig config) service( ServletRequest , ServletResponse)
destroy()
getServletConfig()
getServletInfo()
l l
-
8/6/2019 Building Web Applications Using Servlets_java30
41/132
JavaTM Education & Technology ServicesCopyright Information Technology Institute 41
Servlet Example The following code is a typical implementation of the interface:
import javax.servlet.*;
import java.io.*;public class MyServlet implements Servlet
{
public voidinit(ServletConfig config) throws ServletException
{
System.out.println("I am inside the init method");}
public voidservice(ServletRequest request,
ServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(
Welcome to Servlets and JSP Course");System.out.println("I am inside the service method");
}
Write to the response
S l E l d
-
8/6/2019 Building Web Applications Using Servlets_java30
42/132
JavaTM Education & Technology ServicesCopyright Information Technology Institute 42
Servlet Example contd
public voiddestroy()
{System.out.println(I am inside the destroy method");
}
public String getServletInfo()
{return null;
}
public ServletConfig getServletConfig()
{return null;
}
}
Si l Th dM d l I t f
-
8/6/2019 Building Web Applications Using Servlets_java30
43/132
JavaTM Education & Technology ServicesCopyright Information Technology Institute 43
SingleThreadModel Interface
The SingleThreadModel interface is used to prevent
simultaneous access to instance variables by multiplethreads.
Only one request thread accesses a single instance of the
servlet at a time.
The server queues the requests and passes them one at atime to a single servlet instance.
Or the server creates a pool of multiple instances, eachhandles one request at a time.(however, unsafe).
-
8/6/2019 Building Web Applications Using Servlets_java30
44/132
S l tC fi I t f
-
8/6/2019 Building Web Applications Using Servlets_java30
45/132
JavaTM Education & Technology ServicesCopyright Information Technology Institute 45
ServletConfig Interface
The ServletConfig interface is used by a servlet to obtain
any configuration information written specifically for it in thedeployment descriptor file (web.xml).
It is passed by the servlet container to the init(..) method
as parameter.
Such configuration information is better written in the xml fileinstead of hard coding it inside the servlets code.
Such approach makes it easy to alter such information after theservlets source code has been compiled.
Each servlet is passed its own set of configuration parameters.
S l tC fi I t f td
-
8/6/2019 Building Web Applications Using Servlets_java30
46/132
JavaTM Education & Technology ServicesCopyright Information Technology Institute 46
ServletConfig Interface contd
Configuration parameters (init params) can be written inside
the web.xml file as follows:
MyServlet
ServletConfigTest
AdminEmail
The whole tag is repeated for each parameter.
S l tC fi I t f td
-
8/6/2019 Building Web Applications Using Servlets_java30
47/132
JavaTM Education & Technology ServicesCopyright Information Technology Institute 47
ServletConfig Interface contd
The ServletConfig interface has 4 methods:
Enumeration getInitParmeterNames()
String getInitParameter(String paramName)
String getServletName()
ServletContext getServletContext()
-
8/6/2019 Building Web Applications Using Servlets_java30
48/132
-
8/6/2019 Building Web Applications Using Servlets_java30
49/132
JavaTM Education & Technology ServicesCopyright Information Technology Institute 49
Lab Exercise
Assignment
-
8/6/2019 Building Web Applications Using Servlets_java30
50/132
JavaTM Education & Technology ServicesCopyright Information Technology Institute 50
Assignment
Use servletConfig to pass variables fromweb.xml to the servlet and display it in theresponse.
Like DB connection Statement. DB user name and password.
DatabaseAddress
163.121.12.25
userName
iTi
password
iTi
ServletContext Interface
-
8/6/2019 Building Web Applications Using Servlets_java30
51/132
JavaTM Education & Technology ServicesCopyright Information Technology Institute 51
ServletContext Interface
The context is the environment in which the servlets of a webapplication run.
There is only one context per web application (i.e. all theservlets of a web application have references to the samecontext).
The deployment descriptor (web.xml) can include tags (contextparams) that are general for the whole web application.
The ServletContext interface defines a set of methods that
a servlet uses in order to obtain such context parameters.
ServletContext Interface contd
-
8/6/2019 Building Web Applications Using Servlets_java30
52/132
JavaTM Education & Technology ServicesCopyright Information Technology Institute 52
ServletContext Interface contd
Moreover, a servlet can also bind an object attribute to thecontext (a pair: name and object value), which will beavailable to any other servlet that is part of the same webapplication.
In order to obtain a reference to the context, the followingmethod of the ServletConfig interface is used:
ServletContext getServletContext()
ServletContext Interface contd
-
8/6/2019 Building Web Applications Using Servlets_java30
53/132
JavaTM Education & Technology ServicesCopyright Information Technology Institute 53
ServletContext Interface cont d
Context parameters of a web application (context params)
can be written inside the web.xml file as follows:
DollarExchangeRate5.6
....
The whole tag is repeated for eachparameter. It should be placed at the beginning of the file.
ServletContext Interface contd
-
8/6/2019 Building Web Applications Using Servlets_java30
54/132
JavaTM Education & Technology ServicesCopyright Information Technology Institute 54
ServletContext Interface cont d
Commonly used methods:
Enumeration getInitParameterNames() String getInitParameter(String paramName)
Enumeration getAttributeNames()
Object getAttribute(String attName)
void setAttribute(String attName, Object value)
void removeAttribute(String attName)
void log(String msg)
Example
-
8/6/2019 Building Web Applications Using Servlets_java30
55/132
JavaTM Education & Technology ServicesCopyright Information Technology Institute 55
Example
public class servletContext implements Servlet {ServletConfig sConf;public void init(ServletConfig config) throws
ServletException {sConf = config;}public void service(HttpServletRequest
request,HttpServletResponse response)throwsServletException, IOException{ServletContext servletContext = sConf.getServletContext();
PrintWriter out = response.getWriter();String str= servletContext.
getInitParameter(AdminEmail);out.println(AdminEmail is: " + str);
}..}
Example
-
8/6/2019 Building Web Applications Using Servlets_java30
56/132
JavaTM Education & Technology ServicesCopyright Information Technology Institute 56
Example
public class servletContext implements Servlet {
ServletConfig sConf;
public void init(ServletConfig config) throwsServletException {
sConf = config;
}
public void service(ServletRequestrequest,ServletResponse response)throwsServletException, IOException
{
ServletContext servletContext = sConf.getServletContext();
PrintWriter out = response.getWriter();
servletContext.setAttribute(MyPassword,iti);
}
..}
SetterServlet
Example
-
8/6/2019 Building Web Applications Using Servlets_java30
57/132
JavaTM Education & Technology ServicesCopyright Information Technology Institute 57
Example
public class servletContext implements Servlet {ServletConfig sConf;public void init(ServletConfig config) throws
ServletException {sConf = config;}public void service(ServletRequest
request,HttpServletResponse response)throwsServletException, IOException{ServletContext servletContext = sConf.getServletContext();
PrintWriter out = response.getWriter();String str= servletContext.getAttribute(MyPassword);
out.println(MyPassword is: " + str);}..}
GetterServlet
Config & Context
-
8/6/2019 Building Web Applications Using Servlets_java30
58/132
JavaTM Education & Technology ServicesCopyright Information Technology Institute 58
Config & Context
Web Application 1
The Servlet Container
ServletContext
Servlet1
ServletConfig1
Servlet2
ServletConfig2
Web Application 2
ServletContext
Servlet1
ServletConfig1
Servlet2
ServletConfig2
-
8/6/2019 Building Web Applications Using Servlets_java30
59/132
JavaTM Education & Technology ServicesCopyright Information Technology Institute 59
Lab Exercise
Assignment
-
8/6/2019 Building Web Applications Using Servlets_java30
60/132
JavaTM Education & Technology ServicesCopyright Information Technology Institute 60
Assignment
Sharing info between servlets: A servlet willassign a username and password attributes ,and another servlet will display it
Your servlets should read the initializedparameters given to them by
tag in web.xml
Country
Egypt
ServletRequest Interface
-
8/6/2019 Building Web Applications Using Servlets_java30
61/132
JavaTM Education & Technology ServicesCopyright Information Technology Institute 61
ServletRequest Interface
The ServletRequest defines an object that is used to hold
information coming from the user's request, includingparameter name-value pairs, attributes, and an input stream.
Commonly used methods:
Enumeration getParameterNames() String getParameter(String paramName)
String[] getParameterValues(String paramName)
String getRemoteHost()
Sending Request Parameters to a Servlet
-
8/6/2019 Building Web Applications Using Servlets_java30
62/132
JavaTM Education & Technology ServicesCopyright Information Technology Institute 62
Sending Request Parameters to a Servlet
The tag in HTML is used as follows:
Sending parameters in the request
-
8/6/2019 Building Web Applications Using Servlets_java30
63/132
JavaTM Education & Technology ServicesCopyright Information Technology Institute 63
Sending Request Parameters to a Servlet cont d
In order for the servlet to get the parameters from the request,the following code is written in the service(..) method:
public void service(ServletRequest request,ServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter();String str = request.getParameter(MyName");
out.println(The user input is: + str);
}
ServletResponse Interface
-
8/6/2019 Building Web Applications Using Servlets_java30
64/132
JavaTM Education & Technology ServicesCopyright Information Technology Institute 64
ServletResponse Interface
The ServletResponse interface defines an object thatcarries the servers response to the user (i.e. back to theclients browser).
Commonly used methods: PrintWriter getWriter()
setContentType(String mimeType) setContentLength(int len)
ServletResponse Example
-
8/6/2019 Building Web Applications Using Servlets_java30
65/132
JavaTM Education & Technology ServicesCopyright Information Technology Institute 65
ServletResponse Example
Sending response in Excel Sheet Format:
public void service(ServletRequest request,
ServletResponse response)throws ServletException, IOException
{
response.setContentType("application/vnd.ms-excel");
PrintWriter out = response.getWriter();
out.println("\t jan \t feb \t march \t total");out.println("salary \t100 \t200 \t300 \t=sum(B2:D2)");
}
GenericServlet Wrapper Class
-
8/6/2019 Building Web Applications Using Servlets_java30
66/132
JavaTM
Education & Technology ServicesCopyright Information Technology Institute 66
GenericServlet Wrapper Class
The GenericServlet class is a convenient class thatimplements the Servlet interface.
It overrides the required 5 methods, and hence makes yourcode simpler (i.e. you extend the class and only overridethe necessary methods).
-
8/6/2019 Building Web Applications Using Servlets_java30
67/132
JavaTM
Education & Technology ServicesCopyright Information Technology Institute 67
Accessing Databaseswith JDBC
Chapter 4
Chapter 4 Outline
-
8/6/2019 Building Web Applications Using Servlets_java30
68/132
JavaTM
Education & Technology ServicesCopyright Information Technology Institute 68
Review on JDBC
Steps to Work with a Database
Sample Applications of Database Operations
Online SQL Tool
Chapter 4 Outline
Review on JDBC
-
8/6/2019 Building Web Applications Using Servlets_java30
69/132
JavaTM
Education & Technology ServicesCopyright Information Technology Institute 69
Review on JDBC
JDBC API: set of Java interfaces for connecting to anyDBMS and executing SQL statements. Packages are:
java.sql package: basic functionalities.
javax.sql package: advanced functionalities.
JDBC Driver: Vendor-specific implementation of JDBCinterfaces. Every DBMS has JDBC driver(s).
Connection String: A special DBMS-specific string that isused to connect to the database, for example:
MS Access:jdbc:odbc:DataSourceName
Oracle (thin):jdbc:oracle:thin:@host:port:sid
Steps to Work with a Database
-
8/6/2019 Building Web Applications Using Servlets_java30
70/132
JavaTM
Education & Technology ServicesCopyright Information Technology Institute 70
Steps to Work with a Database
1. Load (register) the JDBC driver.
2. Obtain a connection.
3. Execute query statements.
4. Process results if any (ResultSet).
Steps to Work with a Database contd
-
8/6/2019 Building Web Applications Using Servlets_java30
71/132
JavaTM
Education & Technology ServicesCopyright Information Technology Institute 71
Steps to Work with a Database cont d
First Step: Put the driver (if jar file) in WEB-INF/lib for deploying (and in
CLASSPATH environment variable for development). The driver could also be put in the common/lib folder (will be common
among all web applications).
Register an object of the driver, for example:
DriverManager.registerDriver(
new sun.jdbc.odbc.JdbcOdbcDriver());
Second Step: Obtain the connection through the Connection interface, for example:
Connection con = DriverManager.getConnection("jdbc:odbc:mydsn",userName",password");
Steps to Work with a Database contd
-
8/6/2019 Building Web Applications Using Servlets_java30
72/132
JavaTM
Education & Technology ServicesCopyright Information Technology Institute 72
Steps to o t a atabase co t d
Third Step: Create a statement and execute queries using either
executeUpdate(..) or executeQuery(..), for example:Statement s = connection.createStatement();
ResultSet rs= s.executeQuery(select * from Emp);
Fourth Step: After obtaining the ResultSet, extract data through the getter methods,
for example:while(rs.next())
{
out.println(rs.getInt(1) + : + rs.getString( FNAME
));
}
Note: You can get information about the retrieved ResultSetby using the method: getMetaData()
Steps to Work with a Database contd
-
8/6/2019 Building Web Applications Using Servlets_java30
73/132
JavaTM
Education & Technology ServicesCopyright Information Technology Institute 73
p
Do not forget to close the connection.
By default, only one ResultSet object per Statement
object can be open at the same time.
If the defaultResultSet
object is obtained, then columns
within each row should be read in left-to-right order, andeach column should be read only once.
Inserting Records into the Database
-
8/6/2019 Building Web Applications Using Servlets_java30
74/132
JavaTM
Education & Technology ServicesCopyright Information Technology Institute 74
g
You can insert records using the following SQL statement:insert into Users (FirstName, LastName, UserName, Password)
values(JETS, ITI, jets, iti)
Searching for Records in a Database
-
8/6/2019 Building Web Applications Using Servlets_java30
75/132
JavaTM
Education & Technology ServicesCopyright Information Technology Institute 75
g
You can write an SQL statement that searches for a certainname in the database:
select FirstName, LastName, UserName, Password FROM Users WHEREFirstName LIKE '%keyword% OR LastName LIKE '%keyword%'
Online SQL Tool
-
8/6/2019 Building Web Applications Using Servlets_java30
76/132
JavaTM
Education & Technology ServicesCopyright Information Technology Institute 76
Q
You can now create an online SQL tool that executes any queryon the database and display the result in a text area.
-
8/6/2019 Building Web Applications Using Servlets_java30
77/132
JavaTM
Education & Technology ServicesCopyright Information Technology Institute 77
Lab Exercise
Submit User Details to a Servlet
-
8/6/2019 Building Web Applications Using Servlets_java30
78/132
JavaTM
Education & Technology ServicesCopyright Information Technology Institute 78
Registration : ( add a user to the database)
Write an HTML page that has text input fields for the users data (e.g.name, phone, email, etc), along with a submit button.
Upon pressing the submit button, the page should send the data to aservlet.
The servlet should then get the parameters from the request and add
them to the data base(i.e. show that it were add or not in the responsethat is returned back to the user).
Login :
Write an HTML page that has two text input fields for the users name
and mail, along with a submit button.
Upon pressing the submit button, the page should send the data to aservlet.
Checking the username and password against the database.
Submit User Details to a Servlet
-
8/6/2019 Building Web Applications Using Servlets_java30
79/132
JavaTM
Education & Technology ServicesCopyright Information Technology Institute 79
Display: Bonus
develop a servlet that views data of the products from the database (id,in a well formatted HTML table.
Search: Bonus develop a search servlet for products.
Response in Different Formats
-
8/6/2019 Building Web Applications Using Servlets_java30
80/132
JavaTM
Education & Technology ServicesCopyright Information Technology Institute 80
Develop different servlets that send response in different mime
types (e.g. excel sheet, word document, etc).
Hint: Search on tshe internet for names of famous mime types.
-
8/6/2019 Building Web Applications Using Servlets_java30
81/132
JavaTM
Education & Technology ServicesCopyright Information Technology Institute 81
Getting Familiar with HTTPPackage
Chapter 5
javax.servlet.http.*
-
8/6/2019 Building Web Applications Using Servlets_java30
82/132
JavaTM
Education & Technology ServicesCopyright Information Technology Institute 82
HTTPServlet GenericServlet
HTTPServletRequest ServletRequest
HTTPServletResponse ServletResponse
javax.servlet.http.* (contd)
-
8/6/2019 Building Web Applications Using Servlets_java30
83/132
JavaTM
Education & Technology ServicesCopyright Information Technology Institute 83
Some basic interfaces HttpServletRequest HttpServletResponse HttpSession
Classes Cookie HttpServlet
The HTTPServlet Class
-
8/6/2019 Building Web Applications Using Servlets_java30
84/132
JavaTM
Education & Technology ServicesCopyright Information Technology Institute 84
It extends from javax.servlet.GenericServlet
It contains extra methods like :
doPost() doPut()
doGet () doDelete()
doOptions() doTrace()
The HTTPServlet Class (contd)
-
8/6/2019 Building Web Applications Using Servlets_java30
85/132
JavaTM
Education & Technology ServicesCopyright Information Technology Institute 85
Request
Response
service()
Server HttpServlet
doGet()
doPost()
HttpServlet Example
-
8/6/2019 Building Web Applications Using Servlets_java30
86/132
JavaTM
Education & Technology ServicesCopyright Information Technology Institute 86
The following code demonstrates the use of the doGet(..) method:
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType(text/html);
PrintWriter out = response.getWriter();
out.println(""); out.println("");
out.println("The servlet has received a GET request." +
"Now, click on the button below.");
out.println("
");out.println("");
out.println("");
out.println("");
out.println(""); out.println("");
}
HttpServlet Example contd
-
8/6/2019 Building Web Applications Using Servlets_java30
87/132
JavaTM
Education & Technology ServicesCopyright Information Technology Institute 87
The following code demonstrates the use of the doPost(..) method:
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(""); out.println("");
out.println("The POST method");
out.println("");
out.println("");
out.println("The servlet has received a POST request.Thank you.");
out.println("");
out.println("");
}
HttpServletRequest Interface
-
8/6/2019 Building Web Applications Using Servlets_java30
88/132
JavaTM
Education & Technology ServicesCopyright Information Technology Institute 88
Common methods: Enumeration getHeaderNames()
String getHeader(String headerName)
Enumeration getHeaders(String headerNames)
String getQueryString()
HttpSession getSession(boolean create)
Cookie[] getCookies()
Remember, methods inherited from ServletRequest: Enumeration getParameterNames()
String getParameter(String paramName) String[] getParameterValues(String paramName)
HttpServletResponse Interface
-
8/6/2019 Building Web Applications Using Servlets_java30
89/132
JavaTM
Education & Technology ServicesCopyright Information Technology Institute 89
Common methods: setStatus(int statusCode)
sendRedirect(String newLocation)
sendError(int statusCode, String msg)
addCookie(Cookie cookie)
setHeader(String headerName, String value)
setIntHeader(String headerName, int value) setDateHeader(String headerName, long milliseconds)
Remember, methods inherited from ServletResponse:
PrintWriter getWriter() setContentType(String mimeType)
setContentLength(int len)
Status Code
-
8/6/2019 Building Web Applications Using Servlets_java30
90/132
JavaTM
Education & Technology ServicesCopyright Information Technology Institute 90
You have to set the status code and response headersbefore writing any document content to the response that
will be sent back to the client.
For the parameter of setStatus(..) method, you can
either use explicit numbers of your own, or use the static
constant values defined in the HttpServletResponseinterface (e.g. for status code 404 use SC_NOT_FOUND).
-
8/6/2019 Building Web Applications Using Servlets_java30
91/132
Java
TM
Education & Technology ServicesCopyright Information Technology Institute 91
Lab Exercise
Assignment
-
8/6/2019 Building Web Applications Using Servlets_java30
92/132
Java
TM
Education & Technology ServicesCopyright Information Technology Institute 92
Display Headers of the request sent to yourservlet
Assignment
-
8/6/2019 Building Web Applications Using Servlets_java30
93/132
Java
TM
Education & Technology ServicesCopyright Information Technology Institute 93
Registration : add a user the database. Continue the login assignment of the last chapter by
checking the username and password against thedatabase instead of hard coding the check insidethe servlet. User the request dispatchers forward method to direct the
user to a success page or failure page. Display :develop a servlet that views data employees data
from the database (id, name, email, salary, etc) in a wellformatted HTML table:
Provide the ability to add a new employee, edit, or delete anexisting one.
Search: develop a search servlet ( Bouns )
The sendRedirect Method
-
8/6/2019 Building Web Applications Using Servlets_java30
94/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 94
The sendRedirect(..) method is used to redirect the
browsers client to go to another page other than the one
originally requested.
This is useful in several situations, for example: If the requested page has been migrated to another server or url.
Deciding which page the user will be transferred to after successfullogin. Checking if the browser enables the use of cookies.
The location parameter can either be the relative URL of a
page or its fully qualified URL.
The sendRedirect Method contd
-
8/6/2019 Building Web Applications Using Servlets_java30
95/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 95
The sendRedirect(..) method makes a round trip to the
client and then back to the server.
A brand new request object is created, and the previous one islost.
Any data written to the response before calling it will be lost.
If the calling servlet wishes to maintain some information fromthe old request and propagate it to the new request, then youcan pass the information as a query string appended to the
destination URL:
response.sendRedirect("MySecondServlet?userName="+ userName + "&password=" + password);
sendRedirect Example
-
8/6/2019 Building Web Applications Using Servlets_java30
96/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 96
The following code demonstrates the use of sendRedirect(..) method:
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
.
.
out.println();
out.println("
Username: ");out.println("
Password: ");out.println("
");out.println("");
.
.
}
sendRedirect Example contd
-
8/6/2019 Building Web Applications Using Servlets_java30
97/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 97
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
.
.
String userName = request.getParameter("userName");
String password = request.getParameter("password");
if(userName!=null && password!=null &&
userName.equals(user") && password.equals(iti"))
{
response.sendRedirect("WelcomeServletURL");
}else { out.println(Login Failed, please try again.); }
.
.
}
Sending Special Characters
-
8/6/2019 Building Web Applications Using Servlets_java30
98/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 98
Some characters have special meanings to HTML, forexample .
To be able to display such characters in your response,you have to encode them as follows: < is replaced by: <
> is replaced by: >
White spaces are replaced by:  
& is replaced by: &
is replaced by: "
Populating HTML Elements with Values
-
8/6/2019 Building Web Applications Using Servlets_java30
99/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 99
Explicit values example:
Using variables example:
out.println("");
ORout.println("");
out.println("");
Response Buffer
-
8/6/2019 Building Web Applications Using Servlets_java30
100/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 100
For committing a response, a servlet sends the string outputonly once when it finishes processing or when the buffer is full.
Enabling/Increasing the size of the response buffer is useful inenhancing the servlets performance in case of large response
content.
It is ON by default and the default size is 8192 characters
You can can specify the buffer size of the response, using the
method: response.setBufferSize(..)
Note: Call this method before writing any output to theresponse.
RequestDispatcher Interface
-
8/6/2019 Building Web Applications Using Servlets_java30
101/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 101
The RequestDispatcher interface has 2 methods only:
include(ServletRequest request,
ServletResponse response)
forward(ServletRequest request,
ServletResponse response)
-
8/6/2019 Building Web Applications Using Servlets_java30
102/132
RequestDispatcher - forward
-
8/6/2019 Building Web Applications Using Servlets_java30
103/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 103
The forward(..) method passes the processing of an
HTTP request from the current servlet to another servlet or
JSP (i.e. gives up the control for another servlet or jsp).
It is up to the new servlet or JSP to write to the responseobject and then commit it to the client.
Any output written to the response object by the originalservlet will be lost (i.e. dont write to the response before
forwarding to another servlet).
The original servlet can perform some initial tasks on therequest object before forwarding it (e.g. put additionalattributes on it, which will be used by the new servlet or jsp).
Using RequestDispatcher
-
8/6/2019 Building Web Applications Using Servlets_java30
104/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 104
There are two ways to get a dispatcher for the desireddestination servlet or page. Either from the request, or from
the context.
From the ServletRequest: getRequestDispatcher(String path)
//relative path or fully qualified path
From the ServletContext: getRequestDispatcher(String fullPath)
// fully qualified path within the context, beginning with /
getNamedDispatcher(String servletName)
// the servlet name in the web.xml file
Using RequestDispatcher - Example
-
8/6/2019 Building Web Applications Using Servlets_java30
105/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 105
The following code demonstrates the use of the RequestDispather:
RequestDispatcher rd =
request.getRequestDispatcher("SecondServletURL");
rd.include(request, response);
OR:
rd.forward(request, response);
Note: If you use include or forwardfrom a doPost method, then thedoPost method of the second servlet will be invoked. If you use themfrom a doGet method, then the doGet method of the second servlet will
be invoked. Therefore, it is advisable to implement both doGet anddoPost in the destination servlet (write the code in one of the two
methods, and call it from the other method).
Page Transfer through RequestDispatcher
-
8/6/2019 Building Web Applications Using Servlets_java30
106/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 106
Include headers and footers to your pagePrintWriter out = response.getWriter();
// add Header
out.println(This the Header");
// real processingrequest.setAttribute("username",ITI");
RequestDispatcher rd =request.getRequestDispatcher("DispatcherServlet2");
rd.include(request, response);
// back to add footer
out.println(This the Footer");
-
8/6/2019 Building Web Applications Using Servlets_java30
107/132
-
8/6/2019 Building Web Applications Using Servlets_java30
108/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 108
Lab Exercise
Login and Error Servlets
-
8/6/2019 Building Web Applications Using Servlets_java30
109/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 109
Update a login page (either an html page or a dynamic pagegenerated by the doGet(..) method of a servlet).
Upon submitting the login form, the user should be redirectedto a welcome servlet (in case of successful login).
If the login data is incorrect,display a colored error messageon the login page.
Including Header and Footer
-
8/6/2019 Building Web Applications Using Servlets_java30
110/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 110
Create header page and a footer page and then include themin your servlet (at the beginning and end). Bonus
Forwarding to Another Servlet
-
8/6/2019 Building Web Applications Using Servlets_java30
111/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 111
Create a servlet that forwards to another servlet.
Try to make the first servlet write to the response beforeforwarding it to the second servlet, and then see whathappens.
-
8/6/2019 Building Web Applications Using Servlets_java30
112/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 112
Session Management
Chapter 6
Chapter 6 Outline
-
8/6/2019 Building Web Applications Using Servlets_java30
113/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 113
Session Management Techniques
URL Rewriting
Hidden Fields
Cookies
Session Objects
-
8/6/2019 Building Web Applications Using Servlets_java30
114/132
Session Management Techniques
-
8/6/2019 Building Web Applications Using Servlets_java30
115/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 115
The following techniques can be used separately orcooperatively in order to maintain the clients information
throughout the entire session:
URL rewriting.
Hidden fields.
Cookies.
Session objects.
URL Rewriting
URL rewriting is simply appending token(s) to the URL of
-
8/6/2019 Building Web Applications Using Servlets_java30
116/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 116
URL rewriting is simply appending token(s) to the URL ofthe next page or servlet. It starts by a question mark
Tokens are strings in the form of parameter=value
Tokens are separated by an ampersand (&)
It is an easy way but has the following concerns: Supports up to 2000 characters only.
The parameters are exposed in the URL.
You will need to encode special characters (e.g. spaces to + and
special characters to %XX).
Example:http://www.site.com/mySerevlet?param1=value1¶m2=value2
Hidden Fields
-
8/6/2019 Building Web Applications Using Servlets_java30
117/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 117
Forms can include hidden fields among the normal input fields.
Therefore, information can be stored in hidden fields and thenretrieved from the request in the next page or servlet.
The concern is that the user can view the values of the hiddenfields by viewing the html source of the page from within thebrowser.
Example:out.print("
-
8/6/2019 Building Web Applications Using Servlets_java30
118/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 118
A cookie is a small piece of information (name and value) thatis passed back and forth in the HTTP request and response.
The cookie sent by a servlet to the client will be passed back tothe server when the client requests another page from thesame application.
Cookies are represented as a class in the HTTP package.
To create a cookie you write such code:Cookie c1 = new Cookie("myCookieName", myValue");
Niether the name nor the value can contain commas,semicolons, white space, nor begin with a $ character.
Cookies contd
T dd ki t th
-
8/6/2019 Building Web Applications Using Servlets_java30
119/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 119
To add a cookie to the response:
response.addCookie(c1);
To retrieve a cookie from the request:
Cookie[] cookies = request.getCookies();if(cookies != null)
{ for (int i=0; i
-
8/6/2019 Building Web Applications Using Servlets_java30
120/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 120
Cookies must be added to the response before writing anyother response elements.
Advantages of cookies: The values of the cookies are not directly visible.
You don't need to use a form tag.
Cookies are not a serious security threat.
Concerns about cookies:
The user has the choice to set the browser to refuse cookies.
Privacy: if another user has access to the PC, then he may be able toview the values of stored cookies on the hard disk. Therefore, makesure not to write critical information in the cookie. (Anyway, theres no
security without physical security).
Cookies contd
You can detect whether a browser enables cookies or not and
-
8/6/2019 Building Web Applications Using Servlets_java30
121/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 121
You can detect whether a browser enables cookies or not, anddisplay a message that asks the user to enable cookies.
To detect this, you can do the scenario of adding a cookie tothe response of the first servlet, then redirecting to a secondservlet that checks the existence of the cookie in the request.
To redirect the clients browser to another page you can use
either of the following: response.sendRedirect(..)
Note: in both cases you have to use a relative URL, not a fullyqualified one.
Cookies contd
A cookie can either be stored on session level or on
-
8/6/2019 Building Web Applications Using Servlets_java30
122/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 122
A cookie can either be stored on session level or onpersistence level.
A session level cookie is a cookie that is stored in thebrowsers memory and deleted when the user quits the
browser.
A persistent cookie is stored on the clients hard disk. To
make your cookie persistent, use the methodsetMaxAge(int seconds) before adding it to the
response.
Example: c1.setMaxAge(60*60*24*7); // One week
Session Objects
Th b d f l i i bj
-
8/6/2019 Building Web Applications Using Servlets_java30
123/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 123
The best and most powerful was is to use session objects(defined by the HTTPSession interface).
For each user, the servlet container can create anHttpSession object that is associated with that user only.
A session object acts like a Hashtable into which you canstore any number of key/object pairs.
It is accessible from other servlets or jsp pages in the same
application (per user).
Session Objects Basic Scenario
-
8/6/2019 Building Web Applications Using Servlets_java30
124/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 124
Servlet1
Servlet2
1234
Browser
1
2 4
3
Session Objects Basic Scenario contd
The basic scenario of creating and then using a session object is
-
8/6/2019 Building Web Applications Using Servlets_java30
125/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 125
The basic scenario of creating and then using a session object isas follows:
1. A session object is created by Servlet1 (using the getSession(..)method), where a unique session identifier is generated for it (e.g.jsessionid=1234).
2. Servlet1 implicitly sends the session identifier to the client browser.
3. When the client browser requests another resource from the sameapplication, such as Servlet2, the session identifier is implicitly sentback to the server and passed to Servlet2 in the request object.
4. For Servlet2 to access the session object of this particular client, it usesthe getSession(..) method which automatically retrieves thesession identifier from the request and gains access to the specificsession object associated with that session identifier.
Session Objects - Example
In doPost( ) method of the LoginServlet:
-
8/6/2019 Building Web Applications Using Servlets_java30
126/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 126
In doPost(..) method of the LoginServlet:// After user enters correct login information
HttpSession session = request.getSession(true);session.setAttribute("loggedIn", new String("true"));
response.sendRedirect("ContentServletURL");
In doGet(..) method of the ContentServlet:
HttpSession session = request.getSession(false);if (session == null)
response.sendRedirect(LoginServletUrl);
else
{
String loggedIn = (String) session.getAttribute("loggedIn");
if (!loggedIn.equals("true"))
response.sendRedirect (loginServletUrl);
}
HttpSession
Common methods:
-
8/6/2019 Building Web Applications Using Servlets_java30
127/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 127
Common methods: Enumeration getAttributeNames()
Object getAttribute(String key) void setAttribute(String key, Object value)
void removeAttribute (String key) // e.g. log out
long getCreationTime()
String getId()
long getLastAccessedTime()
void setMaxInactiveInterval(int seconds)
int getMaxInactiveInterval()
ServletContext getServletContext()
void invalidate() boolean isNew()
Invalidating a Session
A session can become invalid in 3 cases:
-
8/6/2019 Building Web Applications Using Servlets_java30
128/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 128
A session can become invalid in 3 cases:
The default session timeout has elapsed (configured in the servletcontainer for all web applications).
The maximum inactive interval time of the session has elapsed (specifiedby calling the method setMaxInactiveInterval(..)).
The programmer decides to invalidate a session (by calling theinvalidate() method).
-
8/6/2019 Building Web Applications Using Servlets_java30
129/132
1. Testing if browser enables cookies
Implement the cookie testing scenario by developing a
-
8/6/2019 Building Web Applications Using Servlets_java30
130/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 130
Implement the cookie testing scenario by developing aservlet that adds a cookie to a response and then
redirecting to another servlet that attempts to retrieve thecookie.
If the user has disabled the use of cookies, send him an
error message asking him to enable cookies. Bonus
2. User login
Keep user s login information on the session and access it
-
8/6/2019 Building Web Applications Using Servlets_java30
131/132
JavaTM Education & Technology Services
Copyright Information Technology Institute 131
Keep user s login information on the session and access it
in another page
References & Recommended Reading
-
8/6/2019 Building Web Applications Using Servlets_java30
132/132
Core Servlets and JSP.
Java for the Web with Servlets, JSP, and EJB.
Manning JSTL in Action.
Sun presentations.
Oracle presentations.
SCJWD study guide.