0% found this document useful (0 votes)
10 views

Server-Side Programming: Java Servlets: Web Technologies A Computer Science Perspective

Uploaded by

Hari Haraan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Server-Side Programming: Java Servlets: Web Technologies A Computer Science Perspective

Uploaded by

Hari Haraan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 100

WEB TECHNOLOGIES

A COMPUTER SCIENCE PERSPECTIVE

JEFFREY C. JACKSON

Chapter 6
Server-side Programming:
Java Servlets

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Server-side Programming
• The combination of
– HTML
– JavaScript
– DOM
is sometimes referred to as Dynamic HTML
(DHTML)
• Web pages that include scripting are often
called dynamic pages (vs. static)

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Server-side Programming
• Similarly, web server response can be
static or dynamic
– Static: HTML document is retrieved from the
file system and returned to the client
– Dynamic: HTML document is generated by a
program in response to an HTTP request
• Java servlets are one technology for
producing dynamic server responses
– Servlet is a class instantiated by the server to
produce a dynamic response
Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Servlet Overview

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Servlet Overview
1. When server starts it instantiates servlets
2. Server receives HTTP request, determines
need for dynamic response
3. Server selects the appropriate servlet to
generate the response, creates
request/response objects, and passes them to
a method on the servlet instance
4. Servlet adds information to response object via
method calls
5. Server generates HTTP response based on
information stored in response object

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Hello World! Servlet

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Hello World! Servlet
All servlets we will write
are subclasses of
HttpServlet

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Hello World! Servlet

Server calls doGet() in response to GET request

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Hello World! Servlet

Interfaces implemented by request/response objects

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Hello World! Servlet

Production servlet should


catch these exceptions

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Hello World! Servlet
• JWSDP Tomcat server exception
handling:
– Stack trace appended to
logs/jwsdp_log.*.txt
– HTML document returned to client may (or
may not) contain partial stack trace
• Servlet output to System.out.print(),
printStackTrace(), etc. is appended
to logs/launcher.server.log
Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Hello World! Servlet

First two
things done
by typical servlet;
must be in this
order

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Hello World! Servlet

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Hello World! Servlet

HTML generated by calling print() or


println() on the servlet’s
PrintWriter object

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Hello World! Servlet

Good practice to explicitly close


the PrintWriter when done

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Servlets vs. Java Applications
• Servlets do not have a main()
– The main() is in the server
– Entry point to servlet code is via call to a
method (doGet() in the example)
• Servlet interaction with end user is indirect
via request/response object APIs
– Actual HTTP request/response processing is
handled by the server
• Primary servlet output is typically HTML

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
The body of a doGet() method generally performs the
following actions in the order shown:

• Set the HTTP Content-Type header of the response.


The MIME type portion of this header will typically be
text/html, and it is also good practice to include the type
of character encoding used, as shown (the default
character encoding is ISO-8859-1).
• Obtain a PrintWriter object from the
HttpServletResponse parameter object by calling this
object’s getWriter() method. The getWriter() method
must not be called before the Content-Type is set by a
call to setContentType().
• Output a valid HTML document to the PrintWriter object.
• Close the PrintWriter object.

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Running Servlets
• Simple way to run a servlet (better later):
1. Compile servlet (make sure that JWSDP
libraries are on path)
2. Copy .class file to shared/classes
directory
3. (Re)start the Tomcat web server
4. If the class is named ServletHello,
browse to
http://localhost:8080/servlet/ServletHello

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Dynamic Content

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Dynamic Content

Each time the doGet() method of the HelloCounter servlet


is executed by the web server, a counter variable visits will
be incremented

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Dynamic Content

we are assuming here that when the web server starts it creates a single
instance of the HelloCounter class and executes the doGet() method on
this instance to handle each request for the HelloCounter servlet.

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Dynamic Content
• Potential problems:
– Assuming one instance of servlet on one
server, but
• Many Web sites are distributed over multiple
servers
• Even a single server can (not default) create
multiple instances of a single servlet
– Even if the assumption is correct, this servlet
does not handle concurrent accesses properly
• We’ll deal with this later in the chapter

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Servlet Life Cycle
• Servlet API life cycle methods
– init(): called when servlet is instantiated;
must return before any other methods will be
called
– service(): method called directly by server
when an HTTP request is received; default
service() method calls doGet() (or
related methods covered later)
– destroy(): called when server shuts down

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Servlet Life Cycle
Example life cycle method:
attempt to initialize visits variable
from file

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Servlet Life Cycle

Exception to be thrown
if initialization fails and servlet
should not be instantiated

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Parameter Data
• The request object (which implements
HttpServletRequest) provides
information from the HTTP request to the
servlet
• One type of information is parameter data,
which is information from the query string
portion of the HTTP request

Query string with


one parameter
Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Parameter Data
• Parameter data is the Web analog of
arguments in a method call:

• Query string syntax and semantics

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Parameter Data
• Query string syntax and semantics
– Multiple parameters separated by &

– Order of parameters does not matter

– All parameter values are strings

Value of arg is empty string

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Parameter Data
• Parameter names and values can be any
8-bit characters
• URL encoding is used to represent non-
alphanumeric characters:

Value of arg is
‘a String’

• URL decoding applied by server to retrieve


intended name or value
Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Parameter Data
• URL encoding algorithm

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Parameter Data

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Parameter Data

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Parameter Data
Must escape XML special characters in
all user-supplied data before adding to HTML
to avoid cross-site scripting attacks

ampersand, less-than, and greater-than symbols in query strings are


replaced by appropriate entity references. The servlet performs this replacement
by calling a static method escapeXML(String) that belongs to a class
WebTechUtil.
Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Parameter Data

Also need to escape quotes within


attribute values.

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Parameter Data

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
For any application designed to be accessed on the public Web, it is
vitally important that your servlets escape all of the data entered by
users before incorporating that data in the documents generated by
your servlets.
•Consider the following scenario. You have written a Web application
that receives user comments via an HTML form and displays the
comments— without escaping—on a public Web page.
• A malicious user, Mal, enters a “comment” on your form that contains
an HTML script element.
•When another user, Mark, visits the page displaying comments, the
content of the script element will be executed by Mark’s browser. The
script could then take various malicious actions: modifying (via the
DOM) content and links on the comments page displayed in Mark’s
browser, redirecting Mark’s browser to another page entirely, even
transmitting Mark’s cookie information (which might include session
information) to a server operated by Mal.

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Parameter Data
• Cross-site scripting
Comment containing
Attacker <script> element

Blogging Web
site

Document containing
Victim attacker’s comment (and script)

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Cross-site scripting
Cross-site scripting (XSS)

How it works Attackers inject malicious code into a website, which


is then executed when a user visits the site

What it can do Attackers can access cookies, session tokens, and


other sensitive data, impersonate the user, and more

How websites are vulnerable Websites are vulnerable if they display user-supplied
data without sanitizing it

How attackers can insert code Attackers can add code to the end of a URL or post it
directly to a page that displays user-generated
content

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Parameter Data

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Parameter Data
• A form automatically generates a query
string when submitted
– Parameter name specified by value of name
attributes of form controls

– Parameter value depends on control type

Value for checkbox


specified by value attribute

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Parameter Data

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Parameter Data

username

lifestory

boxgroup1 (values same as labels)


doit

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Parameter Data
• Query string produced by browser (all one
line):

Checkbox parameters have same name values;


only checked boxes have corresponding parameters

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Parameter Data
• GET vs. POST method for forms:
– GET:
• Query string is part of URL
• Length of query string may be limited
• Recommended when parameter data is not stored
but used only to request information (e.g., search
engine query)
– The URL can be bookmarked or emailed and the same
data will be passed to the server when the URL is
revisited

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Parameter Data

Browser content copyright 2004 Google, Inc. Used by permission.

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Parameter Data
• GET vs. POST method for forms:
– POST:
• Query string is sent as body of HTTP request
• Length of query string is unlimited
• Recommended if parameter data is intended to
cause the server to update stored data
• Most browsers will warn you if they are about to
resubmit POST data to avoid duplicate updates

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Parameter Data

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Sessions
• Many interactive Web sites spread user
data entry out over several pages:
– Ex: add items to cart, enter shipping
information, enter billing information
• Problem: how does the server know which
users generated which HTTP requests?
– Cannot rely on standard HTTP headers to
identify a user

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Sessions

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Sessions

Server sends back


new unique
session ID when
the request has
none

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Sessions

Client that supports


session stores the
ID and sends it
back to the server
in subsequent
requests

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Sessions

Server knows
that all of these
requests are
from the same
client. The
set of requests
is known as a
session.

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Sessions

And the server


knows that all
of these
requests are
from a different
client.

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Sessions

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Sessions

Three web
pages produced
by a single servlet

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Sessions
• Session attribute methods:
– setAttribute(String name, Object
value): creates a session attribute with the
given name and value
– Object getAttribute(String name):
returns the value of the session attribute
named name, or returns null if this session
does not have an attribute with this name

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Sessions

,,, Session attribute is a


name/value pair

getSession()-Returns HttpSession object associated


with this HTTP request.
• Creates new HttpSession object if no
session ID in request or no object with
this ID exists
• Otherwise, returns previously created
object
Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Sessions

,,,

Session attribute will


have null value until
a value is assigned

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Sessions

,,,

Generate
sign-in form
if session is
new or
signIn
attribute has no value,
weclome-back page
otherwise.

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Sessions

Sign-in form

Welcome-back
page

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Sessions

Second argument
(“Greeting”) used as
action attribute value
(relative URL)

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Sessions

Form will be sent using POST HTTP


method (doPost() method will be called)

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Sessions

Text field containing


user name is named
signIn

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Sessions

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Sessions


Retrieve
signIn
parameter value

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Sessions

Normal
processing:
signIn
parameter
is present in
HTTP request

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Sessions

Generate
HTML for
response

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Sessions

Thank-you page Must escape


XML special
characters in
user input

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Sessions

Assign a
value to the
signIn session
attribute

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Sessions

Error
processing
(return user
to sign-in form)

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Sessions
• By default, each session expires if a
server-determined length of time elapses
between a session’s HTTP requests
– Server destroys the corresponding session
object
• Servlet code can:
– Terminate a session by calling
invalidate() method on session object
– Set the expiration time-out duration (secs) by
calling setMaxInactiveInterval(int)
Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Four techniques used in
Session tracking:

•Cookies: Session ID stored in the user's browser.


•URL Rewriting: Session ID appended to the URL.
•Hidden Form Fields: Session ID embedded in forms.
•SSL Session Tracking: Utilizes the SSL session for tracking, secure but
short-lived.

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Cookies
• Cookies are small pieces of data stored by the
user's browser.
• When a user logs in or starts a session, the
server sends a Set-Cookie header with a unique
session ID.
• The browser stores this cookie, and every time the
user sends a request, the browser includes this
cookie in the Cookie header.
Set-Cookie: JSESSIONID=ABC123; Path=/; HttpOnly
On subsequent requests, the browser will send:
Cookie: JSESSIONID=ABC123

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Cookies

•Advantages:
•Persistent storage across sessions if not set to expire.
•Simple to implement.
•Disadvantages:
•Privacy concerns: Users can disable cookies.
•Vulnerable to attacks like Cross-Site Scripting (XSS) and Cross-Site Request
Forgery (CSRF).

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Cookies
• Servlets can set cookies explicitly
– Cookie class used to represent cookies
– request.getCookies() returns an array of
Cookie instances representing cookie data in
HTTP request
– response.addCookie(Cookie) adds a
cookie to the HTTP response

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Cookies

Cookies are expired by


client (server can request
expiration date)

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Cookies

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Cookies

Return array of cookies


contained in HTTP request

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Cookies

Search for
cookie
named
COUNT and
extract value
as an int

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Cookies

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Cookies

Send
replacement
cookie value
to client
(overwrites
existing cookie)

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Cookies

Should call
addCookie()
before writing
HTML

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Cookies
Privacy issues

HTTP request to
intended site Web site
providing
requested
HTTP response:
content
HTML document
Client
including ad <img>
HTTP request for
ad image
Image
plus Set-Cookie Web site
in response: providing
third-party cookie banner
ads

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Step 1: User visits Blog A, which has ads from Ad Network X.
Step 2: Blog A loads the ads, and Ad Network X places a cookie in the user's browser.
Step 3: User clicks a link on Blog A to go to Website B.
Step 4: When the user arrives at Website B, the HTTP referer header indicates that they
came from Blog A.
Step 5: Ad Network X, which serves ads on both Blog A and Website B, now knows that
the user visited both websites, based on the referer header and the cookie it previously
stored.

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Cookies
Privacy issues
Second
HTTP request to 2nd Web site
intended site providing
Web site requested
providing content
requested
HTTP response:
content
HTML document
Client
including ad <img>
HTTP request for
ad image plus Cookie (identifies user)
Image Based on
Web site
providing Referer, I know two
banner Web sites that
ads this user has
visited
Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Cookies
Privacy issues
• Due to privacy concerns, many users
block cookies
– Blocking may be fine-tuned. Ex: Mozilla
allows
• Blocking of third-party cookies
• Blocking based on on-line privacy policy
• Alternative to cookies for maintaining
session: URL rewriting

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
URL Rewriting

• Session IDs are appended to the URL of each request. This allows
the server to track the session by reading the session ID from the
URL.
• The session ID is appended to each URL as a query parameter. For
example:

<a href="http://example.com/home.jsp;jsessionid=ABC123">Home</a>
On the server side, the application reads the jsessionid parameter from
the URL to identify the session.
• Advantages:Works even if the user's browser does not accept cookies.
• Disadvantages:Session IDs are exposed in URLs, which can be captured
in server logs or by attackers.Harder to manage as URLs can become
cluttered, and session IDs are difficult to secure.

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Hidden form fields

• The session ID is embedded in hidden fields within HTML forms.


When the form is submitted, the session ID is sent to the server as
part of the form data.
• The server embeds the session ID in a hidden input field in an
HTML form. For example:
<form action="process.jsp" method="POST">
<input type="hidden" name="sessionID" value="ABC123">
<!-- Other form fields -->
</form>
When the form is submitted, the session ID is sent in the POST
request.

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
Hidden form fields

Advantages:Does not rely on cookies, so it works when cookies are disabled.

Disadvantages:Only works for form submissions, not for other types of requests
like hyperlink clicks.Inconvenient for complex interactions, such as AJAX
requests.

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
SSL Session Tracking
• This method relies on the secure connection between the client and
the server using SSL/TLS (HTTPS). The server uses the SSL
session ID assigned to the client as the basis for tracking.
• When a secure SSL connection is established, an SSL session is
created with a unique session ID. The server can use this SSL
session ID to track the user throughout the connection.
Advantages: No need for session identifiers in cookies or URLs.
Secure because it operates over HTTPS.
Disadvantages: SSL session expires when the connection is closed,
so it's only viable during a continuous SSL session.

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
More Servlet Methods

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
More Servlet Methods

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
More Servlet Methods

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
More Servlet Methods

Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved. 0-13-185603-0
JDBC
JDBC API is a Java API that can access any kind of tabular data, especially data stored in a Relational Database.
Common tasks:
•Making a connection to a database.
•Creating SQL or MySQL statements.
•Executing SQL or MySQL queries in the database.
•Viewing & Modifying the resulting records.

JDBC is a specification that provides a complete set of interfaces that allows for portable access to an underlying database.
Java Applications, Java Servlets, JSP etc.,

All of these different executables are able to use a JDBC driver to access a database, and take advantage of the stored data.
JDBC provides the same capabilities as ODBC, allowing Java programs to contain database-independent code.

JDBC Architecture consists of two layers −

•JDBC API − This provides the application-to-JDBC Manager connection.


•JDBC Driver API − This supports the JDBC Manager-to-Driver Connection.
The JDBC API uses a driver manager and database-specific drivers to provide transparent connectivity to heterogeneous
databases.

The JDBC driver manager ensures that the correct driver is used to access each data source.
The driver manager is capable of supporting multiple concurrent drivers connected to multiple heterogeneous databases.
JDBC
The JDBC API provides the following interfaces and classes −

DriverManager − This class manages a list of database drivers.


Matches connection requests from the java application with the proper database driver using communication sub protocol. The
first driver that recognizes a certain subprotocol under JDBC will be used to establish a database Connection.

Driver − This interface handles the communications with the database server.
Interaction happens directly with Driver objects very rarely.
Instead, DriverManager objects are used, which manages objects of this type. It also abstracts the details associated with
working with Driver objects.

Connection − This interface with all methods for contacting a database.


The connection object represents communication context, i.e., all communication with database is through connection object
only.

Statement − use objects created from this interface to submit the SQL statements to the database.
Some derived interfaces accept parameters in addition to executing stored procedures.

ResultSet − These objects hold data retrieved from a database after SQL query is executed using Statement objects. It acts as an
iterator to allow you to move through its data.

SQLException − This class handles any errors that occur in a database application
JDBC
The programming involved to establish a JDBC connection is fairly simple.
simple four steps −
Import JDBC Packages − Add import statements to your Java program to import required classes in your Java code.
Register JDBC Driver − This step causes the JVM to load the desired driver implementation into memory so it can fulfill your JDBC
requests.
Database URL Formulation − This is to create a properly formatted address that points to the database to which you wish to
connect.
Create Connection Object − Finally, code a call to the DriverManager object's getConnection( ) method to establish actual
database connection.

Import JDBC Packages


JDBC package, which allows you to select, insert, update, and delete data.
import java.sql.* ;
Register JDBC Driver
Registering the driver is the process by which the driver's class file is loaded into the memory, so it can be utilized as an
implementation of the JDBC interfaces.
Registration should be done only once in your program.
Class.forName()
Register a driver is to use Java's Class.forName() method, to dynamically load the driver's class file into memory, which
automatically registers it. This method is preferable because it allows you to make the driver registration configurable and
portable. Eg., Class.forName("com.mysql.cj.jdbc.Driver");
JDBC
Database URL Formulation
After loading the driver, connection is established using the DriverManager.getConnection() method.

getConnection(String url)
getConnection(String url, Properties prop)
getConnection(String url, String user, String password)

Here each form requires a database URL. A database URL is an address that points to your database.
Formulating a database URL is where most of the problems associated with establishing a connection occurs.
Eg., getConnection("jdbc:mysql://localhost:3306/Student","root","")

Closing JDBC Connections


It is required explicitly to close all the connections to the database to end each database session. Else, Java's garbage collector
will close the connection when it cleans up stale objects.

Relying on the garbage collection, especially in database programming, is a very poor programming practice.
But make a habit of always closing the connection with the close() method associated with connection object.
To ensure that a connection is closed, you could provide a 'finally' block in your code. A finally block always executes, regardless
of an exception occurs or not.
To close the above opened connection, you should call close() method as follows −
conn.close();
JDBC
The Statement Objects
Creating Statement Object
Statement object is used to execute a SQL statement, create one using the Connection object's createStatement( ) method

If we created a Statement object, we can then use it to execute an SQL statement with one of its three execute methods.

boolean execute (String SQL):


Returns a boolean value of true if a ResultSet object can be retrieved; otherwise, it returns false.
Use this method to execute SQL DDL statements or when you need to use truly dynamic SQL.

int executeUpdate (String SQL) −


Returns the number of rows affected by the execution of the SQL statement.
Use this method to execute SQL statements for which you expect to get a number of rows affected - for example, an
INSERT, UPDATE, or DELETE statement.

ResultSet executeQuery (String SQL) −


Returns a ResultSet object.
Use this method when you expect to get a result set, as you would with a SELECT statement.
JDBC try
<form action="StudentDetails" > {
Register number:<input type="text" Class.forName("com.mysql.cj.jdbc.Driver");
name="reg"><br>
Mark 1:<input type="text" name="m1"><br> con=DriverManager.getConnection("jdbc:mysql://localh
Mark 2:<input type="text" name="m2"><br> ost:3306/Student","root","");
Mark 3:<input type="text" name="m3"><br> st=con.createStatement();
Mark 4:<input type="text" name="m4"><br> st.executeUpdate("insert into details
Mark 5:<input type="text" name="m5"><br> values('"+reg+"','"+m1+"','"+m2+"','"+m3+"','"+m4+"','"+
<input type="submit"> m5+"')");
</form> out.println("Records Inserted");

}
//Create a servlet and add the code under processRequest catch(Exception e)
method {
String reg=request.getParameter("reg"); out.println(e);
int m1=Integer.parseInt(request.getParameter("m1")); }
int m2=Integer.parseInt(request.getParameter("m2"));
int m3=Integer.parseInt(request.getParameter("m3"));
int m4=Integer.parseInt(request.getParameter("m4"));
int m5=Integer.parseInt(request.getParameter("m5"));
Connection con=null;
Statement st=null;
ResultSet rs=null;

You might also like