Servlets - PowerPoint PPT Presentation

1 / 53
About This Presentation
Title:

Servlets

Description:

Typical Uses of Cookies. Identifying a user ... To read incoming cookies, get them from the request object. ... This includes all cookies sent by the browser. ... – PowerPoint PPT presentation

Number of Views:64
Avg rating:3.0/5.0
Slides: 54
Provided by: csHai
Category:
Tags: cookies | servlets

less

Transcript and Presenter's Notes

Title: Servlets


1
Servlets
  • Web Programming course
  • Dan Goldwasser
  • dgoldwas_at_cs.haifa.ac.il

2
Outline
  • Client server communication
  • Session tracking

3
Client Request Data
  • When a user submits a browser request to a web
    server, it sends two categories of data
  • Form Data Data that the user explicitly typed
    into an HTML form.
  • For example registration information.
  • HTTP Request Header Data Data that is
    automatically appended to the HTTP Request from
    the client.
  • For example cookies, browser type, browser IP
    address.

4
Reading Form Data from Servlets
  • The HttpServletRequest object contains three main
    methods for extracting form data
  • getParameter(str) used to retrieve a single
    form parameter.
  • getParameterValues(str) used to retrieve a list
    of form values, e.g. a list of selected
    checkboxes.
  • getParameterNames() used to retrieve a full
    list of all parameter names submitted by the
    user.
  • We will examine each of these and then explore
    several examples.

5
getParameter(str) Method
  • Used to retrieve a single form parameter.
  • Possible return values
  • String corresponds to the form parameter.
  • Empty String parameter exists, but has no
    value.
  • null parameter does not exist.

public String getParameter(String name)
6
getParameterValues(str) Method
  • Used to retrieve multiple form parameters with
    the same name.
  • For example, a series of checkboxes all have the
    same name, and you want to determine which ones
    have been selected.
  • Returns an Array of Strings.
  • An array with a single empty string indicates
    that the form parameter exists, but has no
    values.
  • null indicates that the parameter does not
    exist.

public String getParameterValues(String name)
7
getParameterNames() method
  • Returns an Enumeration object.
  • By cycling through the enumeration object, you
    can obtain the names of all parameters submitted
    to the servlet.
  • Note that the Servlet API does not specify the
    order in which parameter names appear.

public Enumeration getParameterNames()
8
import java.io. import javax.servlet. import
javax.servlet.http. import java.util. public
class ShowParameters extends HttpServlet
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException
response.setContentType("text/html")
PrintWriter out response.getWriter()
String title "Reading All Request Parameters"
out.println(ServletUtilities.headWithTitle(titl
e) "ltBODY BGCOLOR\"FDF5E6\"gt\n
" "ltH1 ALIGNCENTERgt" title
"lt/H1gt\n" "ltTABLE BORDER1
ALIGNCENTERgt\n" "ltTR
BGCOLOR\"FFAD00\"gt\n"
"ltTHgtParameter NameltTHgtParameter Value(s)")
Output a simple HTML table for displaying the
form parameters.
Continued.
9
Enumeration paramNames request.getParameterN
ames() while(paramNames.hasMoreElements())
String paramName (String)paramNames.next
Element() out.print("ltTRgtltTDgt" paramName
"\nltTDgt") String paramValues
request.getParameterValues(paramName) if
(paramValues.length 1) String
paramValue paramValues0 if
(paramValue.length() 0)
out.println("ltIgtNo Valuelt/Igt") else
out.println(paramValue) else
out.println("ltULgt") for(int i0
iltparamValues.length i)
out.println("ltLIgt" paramValuesi)
out.println("lt/ULgt")
  • First, use getParameterNames() to retrieve an
    Enumeration of all form parameters.
  • Then, iterate through each element within the
    Enumeration.

Continued.
10
out.println("lt/TABLEgt\nlt/BODYgtlt/HTMLgt")
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
doGet(request, response)
11
(No Transcript)
12
HTTP Request Header Data
  • HTTP Request Header Data Data that is
    automatically appended to the HTTP Request from
    the client.
  • For example cookies, browser type, etc,

GET / HTTP/1.1 Accept / Accept-Language
en-us Accept-Encoding gzip, deflate User-Agent
Mozilla/4.0 (compatible MSIE 5.0 Windows NT
DigExt) Host www.yahoo.com Connection Keep-Alive
HTTP request headers
13
Accessing HTTP Headers
  • To access any of these Headers, use the
    HTTPServletRequest getHeader() method.
  • For example
  • String connection req.getHeader(Connection)
  • To retrieve a list of all the Header Names, use
    the getHeaderNames() method.
  • getHeaderNames() returns an Enumeration object.
  • For example
  • Enumeration enum req.getHeaderNames()

14
Additional HTTP Information
  • getMethod()
  • Indicates the request method, e.g. GET or POST.
  • getRequestURI()
  • Returns the part of the URL that comes after the
    host and port. For example, for the URL
    http//randomhost.com/servlet/search, the request
    URI would be /servlet/search.
  • getProtocol()
  • Returns the protocol version, e.g. HTTP/1.0 or
    HTTP/1.1

15
import java.io. import javax.servlet. import
javax.servlet.http. import java.util. public
class ShowRequestHeaders extends HttpServlet
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
response.setContentType("text/html")
PrintWriter out response.getWriter()
String title "Servlet Example Showing Request
Headers" out.println(ServletUtilities.headWit
hTitle(title) "ltBODY
BGCOLOR\"FDF5E6\"gt\n" "ltH1
ALIGNCENTERgt" title "lt/H1gt\n"
"ltBgtRequest Method lt/Bgt"
request.getMethod() "ltBRgt\n"
"ltBgtRequest URI lt/Bgt"
request.getRequestURI() "ltBRgt\n"
"ltBgtRequest Protocol lt/Bgt"
request.getProtocol() "ltBRgtltBRgt\n"
"ltTABLE BORDER1 ALIGNCENTERgt\n"
"ltTR BGCOLOR\"FFAD00\"gt\n"
"ltTHgtHeader NameltTHgtHeader Value")
Continued.
16
Enumeration headerNames request.getHeaderNames(
) while(headerNames.hasMoreElements())
String headerName (String)headerNames.nextElem
ent() out.println("ltTRgtltTDgt"
headerName) out.println(" ltTDgt"
request.getHeader(headerName))
out.println("lt/TABLEgt\nlt/BODYgtlt/HTMLgt")
/ Let the same servlet handle both GET and
POST. / public void doPost(HttpServletReques
t request,
HttpServletResponse response) throws
ServletException, IOException
doGet(request, response)
17
CGI Variables
  • In addition to HTTP Request headers, you can also
    determine additional information about both the
    client and the server
  • IP Address of Client
  • Host Name of Client
  • Server Name
  • Server Port
  • Server Protocol
  • Server Software

18
import java.io. import javax.servlet. import
javax.servlet.http. import java.util. public
class ShowCGIVariables extends HttpServlet
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
response.setContentType("text/html")
PrintWriter out response.getWriter()
String variables
"REMOTE_ADDR", request.getRemoteAddr() ,
"REMOTE_HOST", request.getRemoteHost() ,
"SERVER_NAME", request.getServerName() ,
"SERVER_PORT", String.valueOf(request.getServerPor
t()) , "SERVER_PROTOCOL",
request.getProtocol() ,
"SERVER_SOFTWARE", getServletContext().getServerIn
fo()
Continued.
19
String title "Servlet Example Showing CGI
Variables" out.println(ServletUtilities.headW
ithTitle(title) "ltBODY
BGCOLOR\"FDF5E6\"gt\n" "ltH1
ALIGN\"CENTER\"gt" title "lt/H1gt\n"
"ltTABLE BORDER1 ALIGN\"CENTER\"gt\n"
"ltTR BGCOLOR\"FFAD00\"gt\n"
"ltTHgtCGI Variable NameltTHgtValue")
for(int i0 iltvariables.length i)
String varName variablesi0 String
varValue variablesi1 if (varValue
null) varValue "ltIgtNot specifiedlt/Igt"
out.println("ltTRgtltTDgt" varName "ltTDgt"
varValue) out.println("lt/TABLEgtlt/BODYgtlt
/HTMLgt")
20
Generating the Server Response
  • Servlets can return any HTTP response they want.

HTTP/1.1 200 OK Date Mon, 06 Dec 1999 205426
GMT Server Apache/1.3.6 (Unix) Last-Modified
Fri, 04 Oct 1996 140611 GMT Content-length
327 Connection close Content-type text/html
lttitlegtSample Homepagelt/titlegt ltimg
src"/images/oreilly_mast.gif"gt lth1gtWelcomelt/h2gtHi
there, this is a simple web page. Granted, it
may
21
Setting the HTTP Status Code
  • Normally, your Servlet will return an HTTP Status
    code of 200 OK to indicate that everything went
    fine.
  • To return a different status code, use the
    setStatus() method of the HttpServletResponse
    object.
  • Be sure to set the status code before sending any
    document content to the client.

22
Using setStatus()
  • setStatus takes an integer value. But, its best
    to use the predefined integers in the
    HttpServletResponse. Here are a few
  • SC_FORBIDDEN
  • Status code (403) indicating the server
    understood the request but refused to fulfill it.
  • SC_INTERNAL_SERVER_ERROR
  • Status code (500) indicating an error inside the
    HTTP server which prevented it from fulfilling
    the request.
  • SC_NOT_FOUND
  • Status code (404) indicating that the requested
    resource is not available.

23
Sending Redirects
  • You can redirect the browser to a different URL
    by issuing a Moved Temporarily Status Code
  • SC_MOVED_TEMPORARILY Status code (302)
    indicating that the resource has temporarily
    moved to another location.
  • Because this is so common, the HttpServletResponse
    interface also has a sendRedirect() method.
  • Example
  • res.sendRedirect( http//www.yahoo.com)

24
import java.io. import javax.servlet. import
javax.servlet.http. public class
WrongDestination extends HttpServlet public
void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException String
userAgent request.getHeader("User-Agent")
if ((userAgent ! null)
(userAgent.indexOf("MSIE") ! -1))
response.sendRedirect("http//home.netscape.com")
else response.sendRedirect("http//
www.microsoft.com")
25
Servlet Session tracking
  • Cookies
  • Session API Tracking in Java

26
The Potential of Cookies
  • Idea
  • Servlet sends a simple name and value to client.
  • Client returns same name and value when it
    connects to same site (or same domain, depending
    on cookie settings).
  • Typical Uses of Cookies
  • Identifying a user during an e-commerce session
  • Avoiding username and password
  • Customizing a site
  • Focusing advertising

27
Creating Cookies
  • Three steps to creating a new cookie
  • Create a new Cookie Object
  • Cookie cookie new Cookie (name, value)
  • Set any cookie attributes
  • Cookie.setMaxAge (60)
  • Add your cookie to the response object
  • Response.addCookie (cookie)
  • We will examine each of these steps in detail.

28
Sending Cookies to the Client
  • Create a Cookie object.
  • Call the Cookie constructor with a cookie name
    and a cookie value, both of which are strings.
  • Cookie c new Cookie("userID", "a1234")
  • Set the maximum age.
  • To tell browser to store cookie on disk instead
    of just in memory, use setMaxAge (argument is in
    seconds)
  • c.setMaxAge(6060247) // One week
  • Place the Cookie into the HTTP response
  • Use response.addCookie.
  • If you forget this step, no cookie is sent to the
    browser!
  • response.addCookie(c)

29
Reading Cookies
  • To create cookies, add them to the response
    object.
  • To read incoming cookies, get them from the
    request object.
  • HttpServletRequest has a getCookies() method.
  • Returns an array of cookie objects. This
    includes all cookies sent by the browser.
  • Returns a zero-length array if there are no
    cookies.

30
Reading Cookies
  • Once you have an array of cookies, you can
    iterate through the array and extract the one(s)
    you want.
  • Our next few examples illustrate how this is done.

31
Example RepeatVisitor.java
  • This servlet checks for a unique cookie, named
    repeatVisitor.
  • If the cookie is present, servlet says Welcome
    Back
  • Otherwise, servlet says Welcome aboard.

32
Using Cookies to Detect First-Time Visitors
  • public class RepeatVisitor extends HttpServlet
  • public void doGet(HttpServletRequest request,
  • HttpServletResponse response)
  • throws ServletException, IOException
  • boolean newbie true
  • Cookie cookies request.getCookies()
  • if (cookies ! null)
  • for(int i0 iltcookies.length i)
  • Cookie c cookiesi
  • if((c.getName().equals("repeatVisitor"))
  • (c.getValue().equals("yes")))
  • newbie false
  • break

33
Using Cookies to Detect First-Time Visitors
(Continued)
  • String title
  • if (newbie)
  • Cookie returnVisitorCookie
  • new Cookie("repeatVisitor", "yes")
  • returnVisitorCookie.setMaxAge(606024365)
  • response.addCookie(returnVisitorCookie)
  • title "Welcome Aboard"
  • else
  • title "Welcome Back"
  • response.setContentType("text/html")
  • PrintWriter out response.getWriter()
  • // (Output page with above title)

34
(No Transcript)
35
Session API Tracking in Java
  • Servlets include a built-in Session API
  • Enables you to very easily create applications
    that depend on individual user data
  • For example
  • Shopping Carts
  • Personalization Services
  • Maintaining state about the users preferences.

36
Using the Session API
  • Steps to using the Java Session API
  • Get the Session object from the HTTPRequest
    object.
  • Extract Data from the users Session Object
  • Extract information about the session object
  • - e.g. when was the session created, session ID?
  • Add data to the users Session Object.

37
Session Tracking Basics
  • Access the session object
  • Call request.getSession to get HttpSession object
  • HttpSession session request.getSession()
  • Look up information (user data) associated with a
    session.
  • Call getAttribute on the HttpSession object,
  • cast the return value to the appropriate type,
  • and check whether the result is null.

38
Session Tracking Basics
  • Store information in a session.
  • Use setAttribute with a key and a value.
  • Discard session data.
  • Call removeAttribute discards a specific value
    associated with a specified key (This is the
    most common approach used).
  • Call invalidate to discard an entire session (all
    user data) will be lost including data created by
    other servlets or jsp) be careful!.

39
Behind the Scenes
  • When you call getSession()
  • There is a lot going on behind the scenes.
  • Each user is automatically assigned a unique
    session ID.
  • How does this sessionID get to the user?
  • Option 1
  • If the browser supports cookies
  • the servlet will automatically create a session
    cookie
  • and store the session ID within the cookie.
  • (In Tomcat, the cookie is called JSESSIONID)
  • Option 2
  • If the browser does not support cookies,
  • the servlet will try to extract the session ID
    from the URL.

40
Extracting Data From Session
  • The Session object works like a Hash Map
  • Hash Map that enables you to store any type of
    Java object.
  • You can therefore store any number of keys and
    their associated values.
  • To extract an existing object,
  • use the getAttribute() method.

Integer accessCount (Integer)session.getAttribu
te("accessCount")
41
Extracting Data from Session
  • If you want to get a list of
  • all keys (or attributes) associated with a
    Session,use the
  • getAttributeNames() method.
  • returns an Enumeration of all Attribute names
    (keys).

42
Additional Session Info.
  • public String getId()
  • Returns the unique session ID associated with
    this user, e.g. gj9xswvw9p
  • public boolean isNew()
  • Indicates if the session was just created (first
    time to this servlet).
  • public long getCreationTime()
  • Indicates when the session was first created in
    milliseconds since midnight January 1, 1970
    (GMT).
  • public long getLastAccessedTime()
  • Indicates when the session was last sent from the
    client.

43
Adding Data To Session
  • To add data to a session, use the
  • putAttribute() method,
  • and specify the key_name and value.
  • Example
  • session.putAttribute("accessCount", accessCount)
  • To remove a value, you can use the following
  • removeAttribute (String name) method.

44
Terminating Sessions
  • public void invalidate()
  • If the user does not return to a servlet for XX
    minutes,
  • the session is automatically invalidated and
    deleted.
  • If you want to manually invalidate the session,
  • you can call invalidate().
  • For the exact number of Minutes before
    automatic expiration, check the
    getMaxInactiveInterval() method.

45
Example
  • Our example tracks the number of visits for each
    unique visitor.
  • If this is a first time visit,
  • the servlet creates an accessCount of Integer
    Integer Type and assigns it to the Session.
  • If the user has visited before,
  • the servlet extracts the accessCount and
    increments it, and assigns it to the Session.
  • Servlet also displays
  • basic information regarding the session
    including
  • creation time and time of last access.

46
import java.io. import javax.servlet. import
javax.servlet.http. import java.net. import
java.util. public class ShowSession extends
HttpServlet public void doGet(HttpServletReque
st request,
HttpServletResponse response) throws
ServletException, IOException
response.setContentType("text/html")
PrintWriter out response.getWriter()
String title "Session Tracking Example"
HttpSession session request.getSession(true)
String heading
47
Integer accessCount
(Integer)session.getAttribute("accessCount")
if (accessCount null) // new user
accessCount new Integer(0) heading
"Welcome, Newcomer" else // returning
user heading "Welcome Back"
accessCount new Integer(accessCount.intValue()
1) // Integer is an immutable
(nonmodifiable) data structure. So, you can not
modify the old one in-place.//Instead you have
to to allocate a new one and redo setAttribute.
session.putAttribute("accessCount",
accessCount) out.println(ServletUtilities.he
adWithTitle(title) "ltBODY
BGCOLOR\"FDF5E6\"gt\n" "ltH1
ALIGN\"CENTER\"gt" heading "lt/H1gt\n"
"ltH2gtInformation on Your
Sessionlt/H2gt\n" "ltTABLE
BORDER1 ALIGN\"CENTER\"gt\n"
"ltTR BGCOLOR\"FFAD00\"gt\n"
48
" ltTHgtInfo TypeltTHgtValue\n"
"ltTRgt\n" " ltTDgtID\n"
" ltTDgt" session.getId() "\n"
"ltTRgt\n" "
ltTDgtCreation Time\n" " ltTDgt"
new Date(session.getCreationTime
()) "\n" "ltTRgt\n"
" ltTDgtTime of Last Access\n"
" ltTDgt" new
Date(session.getLastAccessedTime()) "\n"
"ltTRgt\n" "
ltTDgtNumber of Previous Accesses\n"
" ltTDgt" accessCount "\n"
"lt/TRgt"
49
"lt/TABLEgt\n"
"lt/BODYgtlt/HTMLgt") / Handle GET and POST
requests identically. / public void
doPost(HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException
doGet(request, response)
50
(No Transcript)
51
(No Transcript)
52
Summary
  • What two categories of client data are there? How
    is each accessed?
  • How can an HTTP response redirect the client to a
    new URL?
  • What is the difference between Java Session
    tracking API to cookies?
  • How are cookies used in a Servlet?
  • What is an HTTPSession object? How is it used?

53
  • Questions?
Write a Comment
User Comments (0)
About PowerShow.com