Servlets: Modified Slides From DR - Sagiv
Servlets: Modified Slides From DR - Sagiv
Part 2
Modified slides from Dr.Sagiv
- Setter methods:
setValue(), setPath(), setDomain(), setMaxAge()
3
An Example
<html>
getname.html
<head><title>Insert your Name</title></head> <body> <h1>What is your name?</h1> <form action="welcomeback" method="get"> <p> <input type="text" name="username" /> <input type="submit" /> </p>
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 < cookies.length; ++i) { if (cookies[i].getName().equals("username")) user = cookies[i].getValue(); } } else res.addCookie(new Cookie("username", user));
6
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("<html><body><h1>Welcome Back " + user + "</h1></body></html>"); }
WelcomeBack.java
Session Cookies
request
request
id1
Web browser 1
Servlet
Create Session
Web server
Session Cookies
request
request
id2
Web browser 2
id2
id1 response
Servlet
Create Session
Web server
10
Session Cookies
request
id1
Web browser 1
id2
response id1 response
Servlet
Web server
Session read/write
11
Session Cookies
request
id2
Web browser 2
id2
response id1 response
Servlet
Web server
Session read/write
12
sessionId
list
13
Use getSession(false) if you do not want to create a new session when no session exists
14
HttpSession Methods
Session data is accessed in a hash-table fashion:
- setAttribute(String name,Object value)
- Where is this value stored?
More methods:
- removeAttribute, getAttributeNames - isNew, invalidate, getId
- getCreationTime, getLastAccessedTime
- getMaxInactiveInterval, setMaxInactiveInterval
15
16
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("<html><head>" + "<link rel=\"stylesheet\" type=\"text/css\"" + " href=\"cartstyle.css\"/></head><body>"); HttpSession session = req.getSession(); if (session.getAttribute("item-list") == null) { out.println("<h1>Hello new visitor!</h1>"); session.setAttribute("item-list", new LinkedList()); } 17 List itemList = (List) session.getAttribute("item-list");
Store.java
18
ShoppingCart.java
20
URL Rewriting
request
request
Servlet
response
Web browser
id1
Web server
<HTML> <A HREF=servletURL;sessID=id1> </HTML>
21
URL Rewriting
request
Servlet
response Session read/write
Web browser 1
id1
Web server
<HTML>
22
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
23
24
25
web.xml
26
27
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
ServletContext Methods
Access initialization parameters:
getInitParameter(String name), getInitParameterNames()
29
ServletContext Methods
Write to the application log:
log(String msg), log(String message, Throwable exception)
30
32
33
34
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);
35
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/
36
40