Servlets Part 2 - PowerPoint PPT Presentation

About This Presentation
Title:

Servlets Part 2

Description:

... accessed in a hash-table fashion: setAttribute(String name,Object value) ... Requests to an image are forwarded to a random image from the directory images/ 37 ... – PowerPoint PPT presentation

Number of Views:86
Avg rating:3.0/5.0
Slides: 57
Provided by: csHu
Category:
Tags: part | servlets

less

Transcript and Presenter's Notes

Title: Servlets Part 2


1
ServletsPart 2
  • Representation and Management of Data on the Web

2
Servlets and Cookies
Cookie Example
3
Servlets and Cookies
  • Java Servlet API provides comfortable mechanisms
    to handle cookies
  • The class javax.servlet.http.Cookie represents a
    cookie
  • Getter methods
  • getName(), getValue(), getPath(), getDomain(),
    getMaxAge(), getSecure()
  • Setter methods
  • setValue(), setPath(), setDomain(), setMaxAge()

4
Servlets and Cookies (cont)
  • Get the cookies from the service request
  • Cookie HttpServletRequest.getCookies()
  • Add a cookie to the service response
  • HttpServletResponse.addCookie(Cookie cookie)

5
An Example
getname.html
lthtmlgt ltheadgtlttitlegtInsert your
Namelt/titlegtlt/headgt ltbodygt lth1gtWhat is your
name?lt/h1gt ltform action"welcomeback"
method"get"gt ltpgt ltinput
type"text" name"username" /gt
ltinput type"submit" /gt lt/pgt
lt/formgt lt/bodygt lt/htmlgt
6
An Example (cont)
WelcomeBack.java
public class WelcomeBack extends HttpServlet
public void doGet(HttpServletRequest req,
HttpServletResponse res) throws
ServletException, IOException String user
req.getParameter("username") if (user
null) // Find the "username" cookie
Cookie cookies req.getCookies()
for (int i 0 cookies ! null i lt
cookies.length i) if
(cookiesi.getName().equals("username"))
user cookiesi.getValue()
else res.addCookie(new Cookie("username",
user))
7
An Example (cont)
if (user null) // No parameter and no
cookie res.sendRedirect("getname.html")
res.setContentType("text/html") PrintWriter
out res.getWriter() out.println("lthtmlgtltbody
gtlth1gtWelcome Back " user
"lt/h1gtlt/bodygtlt/htmlgt")
WelcomeBack.java
8
Session Management with Servlets
9
Session Cookies
Servlet
id1
Web browser 1
Web server
10
Session Cookies
Servlet
id2
id1
Web browser 2
Web server
11
Session Cookies
Servlet
id2
id1
Web browser 1
Web server
12
Session Cookies
Servlet
id2
id1
Web browser 2
Web server
13
sessionId
list
14
Accessing the Session Data
  • The session object is represented by the class
    HttpSession
  • Use the methods getSesssion() or getSession(true)
    of the doXXX request to get the current
    HttpSession object, or to create one if it
    doesnt exist
  • When a new session is created, the server
    automatically add a session cookie to the
    response
  • Use getSession(false) if you do not want to
    create a new session when no session exists

15
HttpSession Methods
  • Session data is accessed in a hash-table fashion
  • setAttribute(String name,Object value)
  • Where is this value stored?
  • Object getAttribute(String name)
  • More methods
  • removeAttribute, getAttributeNames
  • isNew, invalidate, getId
  • getCreationTime, getLastAccessedTime
  • getMaxInactiveInterval, setMaxInactiveInterval

16
Example A Basic Shopping Cart
  • In the following example a basic shopping cart
    for an online store is implemented
  • The application consists of two Servlets
  • Store.java the main store site
  • ShoppingCart.java handles cart manipulation

17
Online-Store Example
Store.java
public class Store extends HttpServlet public
void doGet(HttpServletRequest req,
HttpServletResponse res) throws ServletException,
IOException res.setContentType("text/html
") PrintWriter out res.getWriter()
out.println("lthtmlgtltheadgt"
"ltlink rel\"stylesheet\" type\"text/css\""
" href\"cartstyle.css\"/gtlt
/headgtltbodygt") HttpSession session
req.getSession() if (session.getAttribute(
"item-list") null)
out.println("lth1gtHello new visitor!lt/h1gt")
session.setAttribute("item-list", new
LinkedList()) List itemList
(List) session.getAttribute("item-list")
18
Online-Store Example (cont)
out.println("lth2gtYour Shopping
Cartlt/h2gtltolgt") for (Iterator it
itemList.iterator() it.hasNext())
out.println("ltligt" it.next() "lt/ligt")
out.println("lt/olgt") out.println("ltform
method\"post\" action\"cart\"gt")
out.println("ltpgtAdd itemltinput name\"item\"
type\"text\"/gt" "ltinput
type\"submit\" value\"send\"/gtlt/pgt"
"ltpgtltinput type\"submit\" value\"empty
cart\" " "name\"clear\"/gtlt/pgtlt
/formgt") out.println("lt/bodygtlt/htmlgt")
Store.java
19
Online-Store Example (cont)
ShoppingCart.java
public class ShoppingCart extends HttpServlet
public void doPost(HttpServletRequest req,
HttpServletResponse res) throws
ServletException, IOException
res.setContentType("text/html")
PrintWriter out res.getWriter()
List items (List) req.getSession().getAttribute(
"item-list") out.println("lthtmlgtltheadgt
ltlink rel\"stylesheet\""
" type\"text/css\" href\"cartstyle.css\"/gt"
"lt/headgtltbodygt")
20
Online-Store Example (cont)
if (req.getParameter("clear") ! null)
items.clear() out.println("lth2gtYour
Shopping Cart is Empty!lt/h2gt") else
String item req.getParameter("item")
items.add(item) out.println("lth2gtThe
item ltigt" item
"lt/igt was added to your cart.lt/h2gt")
out.println("lth2gtlta href\"store\"gtRetu
rn to the storelt/agtlt/h2gt")
out.println("lt/bodygtlt/htmlgt")
ShoppingCart.java
21
URL Rewriting
Servlet
id1
Web browser
Web server
ltHTMLgt ltA HREFservletURLsessIDid1gt lt/HTML
gt
22
URL Rewriting
Servlet
id2
id1
Web browser 1
Web server
ltHTMLgt ltA HREFservletURLsessIDid1gt lt/HTMLgt
GET servletURLsessIDid1 HTTP/1.0
23
Servlet URL Rewriting
  • Use the following methods of the doXXX response
    object to rewrite URLs
  • String encodeURL(String url)
  • Use for HTML hyperlinks
  • String encodeRedirectURL(String url)
  • Use for HTTP redirections
  • These methods contain the logic to determine
    whether the session ID needs to be encoded in
    the URL
  • For example, if the request has a cookie, then
    url is returned unchanged
  • Some servers implement the two methods identically

24
Back to our Store
  • The Store example assumes that the client
    supports cookies
  • To fix the program, we should encode the links we
    supply
  • Store.java
  • "ltform method\"post\" action\""
  • res.encodeURL("cart") "\"gt"
  • ShoppingCart.java
  • lta href\"" res.encodeURL("store") "\"gt"

25
The Session Listener
  • The session listener reacts to the following
    events
  • A new session has been created
  • A session is being destroyed
  • To obtain a session listener, implement the
    interface javax.servlet.http.HttpSessionListener

26
Session-Listener Example (cont)
public class CartInitializer implements
HttpSessionListener public void
sessionCreated(HttpSessionEvent se) List
itemList new LinkedList()
se.getSession().setAttribute("item-list",itemList)
itemList.add("A Free Apple")
public void sessionDestroyed(HttpSessionEvent se)

CartInitializer.java
ltlistenergt ltlistener-classgtCartInitializerlt/
listener-classgt lt/listenergt
web.xml
27
The Servlet Context
28
Uses of ServletContext
  • For communicating with the Servlet container
    (e.g., Tomcat server), we use the ServletContext
    object
  • One context is shared among all Web-application
    Servlets
  • Can store Web application initialization
    parameters
  • Can store and manipulate application-shared
    attributes
  • Can be used to access the logger
  • Can be used to dispatch requests to other
    resources

29
ServletContext Methods
  • Access initialization parameters
  • getInitParameter(String name), getInitParameterNam
    es()
  • Read Web-application attributes
  • getAttribute(String name), getAttributeNames()
  • Manipulate Web-application attributes
  • setAttribute(String, Object), removeAttribute(Stri
    ng)
  • Transform context-relative paths to absolute
    paths
  • getRealPath(String path), URL getResource(String
    path)

30
ServletContext Methods
  • Write to the application log
  • log(String msg), log(String message, Throwable
    exception)
  • Get a resource dispatcher (discussed later)
  • RequestDispatcher getRequestDispatcher(String
    path)
  • Name and version of the Servlet container
  • String getServerInfo()

31
Note about ServletContext
  • There is a single ServletContext per Web
    application
  • Different Sevlets will get the same
    ServletContext object, when calling
    getServletContext during different sessions
  • You can lock the context to protect a critical
    section from all Web-application accesses

32
The Request Dispatcher
33
The Request Dispather
  • The RequestDispatcher object is used to send a a
    client request to any resource on the server
  • Such a resource may be dynamic (e.g. a Servlet or
    a JSP file) or static (e.g. a HTML document)
  • To send a request to a resource x, use
  • getServletContext().getRequestDispatcher("x")

34
Request Dispatcher Methods
  • void forward(ServletRequest request,
    ServletResponse response)
  • Forwards a request from a Servlet to another
    resource
  • void include(ServletRequest request,
    ServletResponse response)
  • Includes the content of a resource in the response

35
Passing on Data
  • 3 different ways to pass parameters for the
    forwarded Servlet or JSP
  • Data that will be used only for this request
  • request.setAttribute("key", value)
  • Data will be used for this client (also for
    future requests)
  • session.setAttribute("key", value)
  • Data that will be used in the future for every
    client
  • context.setAttribute("key", value)

36
An Example
  • The Servlet JokesAndImages enables a user to
    choose a random joke or a random image
  • The server has 5 images in the directory images/
    and five jokes (txt files) in the directory
    jokes/
  • Empty requests are forwarded to a HTML file that
    enables the user to choose a joke or an image
  • Requests to a joke are forwarded to the servlet
    Jokes
  • Requests to an image are forwarded to a random
    image from the directory images/

37
Jokes and Images
lthtmlgt ltheadgtlttitlegtImages and
Jokeslt/titlegtlt/headgt ltbodygt lth1gtPlease
Selectlt/h1gt ltform method"post"
action"JokesAndImages"gt lth2gt ltinput
type"submit" name"joke" value"A
Joke" /gt ltinput type"submit"
name"image" value"An Image" /gt
lt/h2gt lt/formgt lt/bodygtlt/htmlgt
imagesJokesOptions.html
38
Jokes and Images (cont)
public class JokesAndImages extends HttpServlet
public void doPost(HttpServletRequest req,
HttpServletResponse res) throws ServletException,
IOException int randomNum 1
Math.abs((new Random()).nextInt() 5) if
(req.getParameter("joke") ! null)
req.setAttribute("jokeNumber", new
Integer(randomNum)) getServletContext().getReq
uestDispatcher("/Jokes").forward(req,res)
else if (req.getParameter("image") ! null)
getServletContext().getRequestDispatcher("/images/
image" randomNum
".gif").forward(req, res) else
getServletContext().getRequestDispatcher
("/imagesJokesOptions.html"). forward(req,res)
public void doGet ...
JokesAndImages.java
39
Jokes and Images (cont)
public class Jokes extends HttpServlet public
void doPost(HttpServletRequest req,
HttpServletResponse res) throws
ServletException, IOException
res.setContentType("text/html") PrintWriter
out res.getWriter() out.println("lthtmlgtltbo
dygtlth1gtA Jokelt/h1gtltpregt") int jokeNum
((Integer) req.getAttribute("jokeNumber")).intValu
e() getServletContext().getRequestDispatcher
("/jokes/joke" jokeNum
".txt").include(req, res)
out.println("\nlt/pregt") out.println("lta
href\"" req.getRequestURL() "\"gtBacklt/agt")
out.println("lt/bodygtlt/htmlgt")
Jokes.java
40
Forwarding versus Redirection
  • SendRedirect requires extra communication on part
    of the client Why?
  • By default, SendRedirect does not preserve
    parameters of the request
  • SendRedirect ends up with a different URL on the
    client
  • Which image will be loaded in the following
    scenario? Servlet /a forwards to
    /jokes/joke1.html and joke1.html includes ltimg
    src"image1.gif".../gt

41
Programmatic Security with Servlets
42
Programmatic-Security Methods
  • Servlet API contains several accessories for
    handling programmatic security
  • getRemoteUser()
  • isUserInRole(String role)
  • getAuthType()
  • These are all methods of HttpServletRequest
  • To enable user authentication (even for public
    URLs), provide a link to some protected page

43
An Example Security Constraints in web.xml
ltsecurity-constraintgt
ltweb-resource-collectiongt
ltweb-resource-namegtFirm Peoplelt/web-resource-namegt
lturl-patterngt/login.htmllt/url-patt
erngt lt/web-resource-collectiongt
ltauth-constraintgt
ltrole-namegtemployeeslt/role-namegt
ltrole-namegtmanagerslt/role-namegt
lt/auth-constraintgt lt/security-constraintgt
web.xml
44
An Example Security Constraints in web.xml
ltlogin-configgt ltauth-methodgtFORMlt/a
uth-methodgt ltform-login-configgt
ltform-login-pagegt/loginlt/form-login-pagegt
ltform-error-pagegt/login?failfaillt/form-erro
r-pagegt lt/form-login-configgt
lt/login-configgt ltsecurity-rolegt
ltrole-namegtmanagerslt/role-namegt
lt/security-rolegt ltsecurity-rolegt
ltrole-namegtemployeeslt/role-namegt
lt/security-rolegt
web.xml
45
public class FirmServlet extends HttpServlet
public void doGet(HttpServletRequest req,
HttpServletResponse res) throws ServletException,
IOException res.setContentType("text/html")
PrintWriter out res.getWriter()
out.println("lthtmlgtltheadgtlttitlegtFirmlt/headgtltbodygt"
) out.println("lth1gtHello.lt/h1gt") String
username req.getRemoteUser()
if(usernamenull) out.println("ltpgtltimg
src\"images/visitor.gif\"/gtlt/pgt")
out.println("lth3gtlta href\"login.html\"gtLoginlt/agtlt
/h3gt") out.println("lt/bodygtlt/htmlgt")
return
FirmServlet
46
if(req.isUserInRole("employees"))
out.println("ltpgtltimg src\"images/employee.gif\"/gt
lt/pgt") out.print("lth2gtWelcome Employee "
username "!lt/h2gt")
if(req.isUserInRole("managers"))
out.println("ltpgtltimg src\"images/manager.gif\"/gtlt
/pgt") out.print("lth2gtExecutive average
salary 42764NIS!lt/h2gt")
out.print("lth3gtlta href\"endsession\"gtLog
Outlt/agtlt/h3gt") out.println("lt/bodygtlt/htmlgt")

FirmServlet
47
public class LoginServlet extends HttpServlet
public void doGet(HttpServletRequest req,
HttpServletResponse res) throws
ServletException, IOException PrintWriter
out res.getWriter() res.setContentType("text
/html") out.println("lthtmlgtltheadgtlttitlegtLogin
lt/titlegtlt/headgtltbodygt") if(req.getParameter("
fail")!null) out.print("lth2gtLogin
Failed. Try Again.lt/h2gt")
out.println("ltform action\"j_security_check\"
method\"post\"gt" "ltpgtLogin ltinput
type\"text\" name\"j_username\"/gtlt/pgt"
"ltpgtPassword ltinput type\"password\"
name\"j_password\"/gtlt/pgt" "ltpgtltinput
type\"submit\" value\"Log In\"/gtlt/pgt"
"lt/formgtlt/bodygtlt/htmlgt")
LoginServlet.java
48
public void doPost(HttpServletRequest req,
HttpServletResponse res) throws
ServletException, IOException
this.doGet(req,res)
LoginServlet.java
ltservletgt ltservlet-namegtLoginlt/servlet-na
megt ltservlet-classgtLoginServletlt/servlet-cla
ssgt lt/servletgt ltservlet-mappinggt
ltservlet-namegtLoginlt/servlet-namegt
lturl-patterngt/loginlt/url-patterngt
lt/servlet-mappinggt
web.xml
49
public class EndSession extends HttpServlet
public void doGet(HttpServletRequest req,
HttpServletResponse res) throws
ServletException, IOException HttpSession
session req.getSession(false)
if(session!null) session.invalidate()
res.sendRedirect("firm")
EndSession.java
ltservletgt ltservlet-namegtEndSessionlt/servle
t-namegt ltservlet-classgtEndSessionlt/servlet-c
lassgt lt/servletgt ltservlet-mappinggt
ltservlet-namegtEndSessionlt/servlet-namegt
lturl-patterngt/endsessionlt/url-patterngt
lt/servlet-mappinggt
web.xml
50
Filters
51
Filters in Servlet API
  • Filters are used to dynamically intercept
    requests and responses
  • A filter that applies to a URL u typically acts
    as follows given a request for u
  • performs some actions before the processing of u
  • passes the request handling to the next filter
  • performs some actions after the processing of u

52
(No Transcript)
53
public final class FilterExample implements
Filter public void init(FilterConfig
filterConfig) throws ServletException
... public void destroy()
... public void doFilter(ServletRequest
req, ServletResponse res, FilterChain chain)
throws IOException, ServletException
... chain.doFilter(request, response)
...
FilterExample.java
54
Registering a Filter
ltfiltergt ltfilter-namegtExample
Filterlt/filter-namegt ltfilter-classgtFilterExa
mplelt/filter-classgt lt/filtergt
ltfilter-mappinggt ltfilter-namegtExample
Filterlt/filter-namegt lturl-patterngt/images/lt
/url-patterngt lt/filter-mappinggt
web.xml
55
What Can we Do with Filters?
  • Examine and log requests
  • Modify request headers and properties
  • Modify the response headers and response data
  • E.g., by replacing the response with a wrapper
  • Content compression
  • Image conversion
  • Block requests
  • And more...

56
Notes About Filters
  • The order of the filters in the chain is the same
    as the order that filter mappings appear web.xml
  • The life cycle of filters is similar to that of
    Servlets
  • Filters typically do not themselves create
    responses, although they can
  • The request and response arguments of doFilter
    are actually of type HttpServletRequest and
    HttpServletResponse
  • The filterConfig is used to read initialization
    parameters
  • Those are set in web.xml
Write a Comment
User Comments (0)
About PowerShow.com