Bài 3: Servlet&Cookie&Session - Lập Trình Mạng Nâng Cao
1. Qu n lý phiên c a ngả ủ ứ
d ngụ
ThS Văn Thiên Hoàng
2. M c đíchụ
Trình bày cách x lý thông tin trong m tử ộ
phiên giao ti p trong servlet và gi a cácế ữ
trang web.
3. Thông tin c n duy trì trong phiênầ
Server c n l u hai lo i thông tin trong m tầ ư ạ ộ
phiên giao ti p.ế
Thông tin v phiên giao ti pề ế
Thông tin c a ng i s d ngủ ườ ử ụ
Http thì không duy trì tr ng thái.ạ
4. Gi i phápả
G i qua l i client – serverử ạ
S d ng các thành ph n n c a formử ụ ầ ẩ ủ
L u tr thông tin phía client.ư ữ
S d ng Cookieử ụ
L u tr thông tin phiên phía serverư ữ
Session
5. Th n ph n n c a formầ ầ ẩ ủ
<input type="hidden" name="sessionID" value="...">
L y giá tr bi n n trong form và g i tr l iấ ị ế ẩ ở ả ạ
đ duy trì thông tin phiên trong trang.ể
• String sessionID = getParameter("sessionID");
• out.println("<input
type="hidden" name="sessionID" value=" +
sessionID + "">");
6. Cookie là gì?
Cookie là m t chu i văn b n d ngộ ỗ ả ạ
name=value.
Cookie đ c l u trên máy client.ượ ư
URL đ c l u trong m i cookie đ browseượ ư ỗ ể
xác đ nh đ a ch server đ g i tr cookie vị ị ỉ ể ở ả ề
phía server.
7. Thao tác v i Cookiesớ
Java Servlet API cung c p b công c đ thao tác v i cookie.ấ ộ ụ ể ớ
L pớ javax.servlet.http.Cookie bi u di n cookie.ể ễ
Ph ng th c l y giá trươ ứ ấ ị
• getName(), getValue(), getPath(), getDomain(),
getMaxAge(), getSecure()…
Ph ng th c thi t l pươ ứ ế ậ
• setValue(), setPath(), setDomain(), setMaxAge()…
L y t t c các cookie t requestấ ấ ả ừ
• Cookie[] HttpServletRequest.getCookies()
G i cookie v clientở ề
• HttpServletResponse.addCookie(Cookie cookie)
8. Các b c t o cookieướ ạ
Ba b c đ t o cookieướ ể ạ
1) T o đ i t ng cookieạ ố ượ
Cookie cookie = new Cookie (name, value);
1) Thi t l p thu c tính cookieế ậ ộ
Cookie.setMaxAge (60);
1) g i cookie v clientở ề
Response.addCookie (cookie)
9. G i cookie v phía clientở ề
T o đ i t ng Cookieạ ố ượ
Cookie c = new Cookie("userID", "a1234");
Thi t l p th i gian s ng c a cookie trên đĩa c ng c aế ậ ờ ố ủ ứ ủ
client (đ n v giây).ơ ị
c.setMaxAge(60*60*24*7); // một tuần
Đ t cookie vào đ i t ng HTTP response đ g i vặ ố ượ ể ở ề
client.
response.addCookie(c);
10. Ví d :ụ
<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>
</form>
</body>
</html>
getname.html
11. Ví dụ
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));
WelcomeBack.java
12. Ví d (ti p theo)ụ ế
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
13. Session là gì?
Gi i pháp đ duy trì d li u g i qua nhi u trangả ể ữ ệ ở ề
Server.ở
Đ l u thông tin, Session t o ra c ch để ư ạ ơ ế ể
qu n lý cookie cho t ng phiên v i m t id đả ừ ớ ộ ể
nh n d ng ho c s d ng URL.ậ ạ ặ ử ụ
19. Truy c p d li u Sessionậ ữ ệ
Đ i t ng session là th hi n c a l pố ượ ể ệ ủ ớ HttpSession.
S d ng ph ng th cử ụ ươ ứ getSesssion() ho cặ
getSession(true) đ l y đ i t ngể ấ ố ượ HttpSession hi nệ
t i ho c t o ra nó n u không có.ạ ặ ạ ế
S d ngử ụ getSession(false) n u không mu n t o raế ố ạ
session m i khi session không t n t i.ớ ồ ạ
20. Các ph ng th c c a HttpSessionươ ứ ủ
D li u Session đ c truy c p b ng b ng băm.ữ ệ ượ ậ ằ ả
- setAttribute(String name,Object value)
- Object getAttribute(String name)
Các ph ng th c khác:ươ ứ
- removeAttribute, getAttributeNames
- isNew, invalidate, getId
- getCreationTime, getLastAccessedTime
- getMaxInactiveInterval, setMaxInactiveInterval
21. Ví d : Shopping Cart c b nụ ơ ả
Ví d v m t shopping cart tr c tuy n cụ ề ộ ự ế ơ
b n g m Servletả ồ
- Store.java: trang chính
- ShoppingCart.java: x lý s ki nử ự ệ
22. Ví d : Online-Storeụ
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());
}
List itemList = (List) session.getAttribute("item-list");
Store.java
24. 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("<html><head><link rel="stylesheet""
+ " type="text/css" href="cartstyle.css"/>"
+ "</head><body>");
ShoppingCart.java
Ví d : Online-Storeụ
25. if (req.getParameter("clear") != null) {
items.clear();
out.println("<h2>Your Shopping Cart is Empty!</h2>");
} else {
String item = req.getParameter("item");
items.add(item);
out.println("<h2>The item <i>" + item +
"</i> was added to your cart.</h2>");
}
out.println("<h2><a href="store">Return to the store</a></h2>");
out.println("</body></html>");
}} ShoppingCart.java
Ví d : Online-Storeụ
26. Vi t vào URLế
Web
browser
Web server
request request
ServletServlet
id1
response response
Create Session
>HTML<…
>A HREF=“servletURL;sessID=id1”<
…>/HTML<
28. Vi t l i Servlet URLế ạ
S d ng các ph ng th c đ vi t vào URLử ụ ươ ứ ể ế
- String encodeURL(String url)
• S d ng cho HTML hyperlinkử ụ
- String encodeRedirectURL(String url)
• S d ng choử ụ HTTP redirection
Các ph ng th c này xác đ nh session IDươ ứ ị
c n đ c mã hóa trong URL.ầ ượ
N u truy v n có cookie thìế ấ url đ c g i vượ ở ề
bình th ng.ườ
29. Ch ng trình Storeươ
Gi s ch ng trình store ch y trên client không h trả ử ươ ạ ỗ ợ
cookie.
Đ gi i quy t, vi c vi t vào URL nên đ c s d ng.ể ả ế ệ ế ượ ử ụ
Store.java
"<form method="post" action="" + res.encodeURL("cart") + "">“
ShoppingCart.java
“<a href="" + res.encodeURL("store") + "">"
30. Session Listener
session listener đ c s d ng đ ph n ngượ ử ụ ể ả ứ
các s ki n liên quan đ n đ n session.ự ệ ế ế
session m i đ c t o.ớ ượ ạ
M t session b h y.ộ ị ủ
Đ s d ng đ c session listener, cài đ tể ử ụ ượ ặ
giao di nệ javax.servlet.http.HttpSessionListener.
31. Ví d : Session-Listenerụ
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
<listener>
<listener-class>CartInitializer</listener-class>
</listener> web.xml
32. Forwarding và Redirection
M c đ nh,ặ ị SendRedirect không đ m b oả ả
tham s c a request đ c g i lên t client.ố ủ ượ ớ ừ
SendRedirect k t thúc khi m t URL khácế ộ
đ c n p client.ượ ạ ở
Forwarding cho phép g i toàn b d li uở ộ ữ ệ
c a request t i trang khác. Đ forward sủ ớ ể ử
d ngụ request Dispatcher.
34. Request Dispather
Đ i t ngố ượ RequestDispatcher đ c s d ngượ ử ụ
đ g i m t client request t i m t trang b tể ở ộ ớ ộ ấ
kỳ (servlet, JSP ho c HTML) server.ặ ở
Đ l y đ i t ng g i request t i ngu nể ấ ố ượ ở ớ ồ x, sử
d ng:ụ
getServletContext().getRequestDispatcher("x")
35. Các ph ng th c c a đ i t ngươ ứ ủ ố ượ
Request Dispatcher
void forward(ServletRequest request,
ServletResponse response)
Chuy n request t servlet t i ngu n khác.ể ừ ớ ồ
void include(ServletRequest request,
ServletResponse response)
Bao g m c n i d ng c a response.ồ ả ộ ụ ủ
36. Chuy n d li uể ữ ệ
3 cách đ chuy n tham s cho Servlet ho c JSPể ể ố ặ
D li u đ c dùng ch cho request này:ữ ệ ượ ỉ
request.setAttribute("key", value);
D li u đ c s d ng cho client (và c cho cácữ ệ ượ ử ụ ả
request v sau)ề
session.setAttribute("key", value);
D li u s đ c dùng trong t ng lai c a m i client.ữ ệ ẽ ượ ươ ủ ỗ
context.setAttribute("key", value);
37. Ví dụ
Servlet JokesAndImages cho phep ng i s d ngườ ử ụ
ch n joke ng u nhiên ho c nh ng u nhiên.ọ ẫ ặ ả ẫ
Server có 5 nh trong th m cả ư ụ images/ và 5 joke
(txt file) trong th m cư ụ jokes/
Các yêu c u r ng s đ c g i t i t p tin HTML nóầ ỗ ẽ ượ ở ớ ậ
cho phép ng i d ng ch n nh ho c joke.ườ ụ ọ ả ặ
Request v i joke đ c g i t i trang servletớ ượ ở ớ Jokes
Requests v i image đ c g i t i m t nh ng uớ ượ ở ớ ộ ả ẫ
nhiên trong th m cư ụ images/