xu ly cookie trong servlet

8 114 0
xu ly cookie trong servlet

Đang tải... (xem toàn văn)

Thông tin tài liệu

http://vietjack.com/  servlets/index.jsp                                                                                                              Copyright  ©  vietjack.com     Xử lý Cookie Servlet Cookie text file lưu giữ máy tính Client chúng giữ cho mục đích theo dõi thơng tin đa dạng Rõ ràng điều là, Java Servlet hỗ trợ HTTP cookie Có bước liên quan việc nhận diện việc phản hồi người dùng: • Server script gửi tập hợp Cookie tới trình duyệt Ví dụ: name, age, số chứng minh thư, … • Trình duyệt lưu giữ thơng tin thiết bị nội để sử dụng thời gian tới • Trong lần tới, trình duyệt gửi u cầu tới Web server, gửi thông tin Cookie tới Server Server sử dụng thơng tin để nhận diện người dùng Chương hướng dẫn bạn cách để thiết lập phục hồi Cookie, cách để truy cập chúng cách để xóa chúng Phân tích Cookie Cookie thường thiết lập HTTP Header (mặc dù JavaScript thiết lập Cookie trực tiếp trình duyệt) Một Servlet, mà thiết lập Cookie, gửi Header trông giống sau: HTTP/1.1 200 OK Date: Fri, 04 Feb 2000 21:03:38 GMT Server: Apache/1.3.9 (UNIX) PHP/4.0b3 Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT; path=/; domain=tutorialspoint.com Connection: close Content-Type: text/html Như bạn thấy, Set-Cookie Header chứa cặp name-value, GMT date, path domain Name value URL mã hóa Trường Expires lệnh tới trình duyệt để “bỏ qua” Cookie sau khoảng date time cho Nếu trình duyệt định cấu hình để lưu giữ Cookie, giữ thơng tin tới Expiry Date Nếu người dùng tới trình duyệt trang mà kết nối với path domain Cookie đó, gửi lại Cookie tới Server Các Header trình duyệt trông giống sau: GET / HTTP/1.0 Connection: Keep-Alive User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc) Host: zink.demon.co.uk:1126 Accept: image/gif, */* Accept- http://vietjack.com/                                                                                                                              Trang  chia  sẻ  các  bài  học  online  miễn  phí  Page  1   http://vietjack.com/  servlets/index.jsp                                                                                                              Copyright  ©  vietjack.com     Encoding: gzip Accept-Language: en Accept-Charset: iso-8859-1,*,utf-8 Cookie: name=xyz Sau đó, Servlet có truy cập tới Cookie thơng qua phương thức request.getCookies(), mà trả mảng đối tượng Cookie Các phương thức Servlet Cookie Bảng liệt kê phương thức hữu ích để bạn sử dụng thao tác Cookie Servlet: STT Phương thức Miêu tả public void setDomain(String pattern) Phương thức thiết lập domain mà Cookie áp dụng, ví dụ: vietjack.com public String getDomain() Phương thức nhận domain mà Cookie áp dụng, ví dụ: vietjack.com public void setMaxAge(int expiry) Phương thức thiết lập thời gian (bằng giây) Cookie hết hạn Nếu bạn khơng thiết lập nó, Cookie tồn cho session public int getMaxAge() Phương thức trả tuổi tối đa Cookie này, xác định giây Theo mặc định, -1 Cookie tồn tới trình duyệt kết thúc public String getName() Phương thức trả tên Cookie Tên bị thay đổi sau tạo public void setValue(String newValue) http://vietjack.com/                                                                                                                              Trang  chia  sẻ  các  bài  học  online  miễn  phí  Page  1   http://vietjack.com/  servlets/index.jsp                                                                                                              Copyright  ©  vietjack.com     Phương thức thiết lập giá trị mà liên kết với Cookie public String getValue() Phương thức nhận giá trị mà liên kết với Cookie public void setPath(String uri) Phương thức thiết lập path mà Cookie áp dụng Nếu bạn khơng xác định path, Cookie trả cho URL thư mục trang tất thư mục phụ public String getPath() Phương thức nhận path mà Cookie áp dụng 10 public void setSecure(boolean flag) Phương thức thiết lập giá trị Boolean có hay khơng Cookie nên gửi qua kết nối mật mã hóa (ví dụ: SSL) 11 public void setComment(String purpose) Phương thức xác định comment mà miêu tả mục đích Cookie Comment hữu ích trình duyệt hiển thị Cookie tới người dùng 12 public String getComment() Phương thức trả Comment miêu tả mục đích Cookie này, trả null Cookie khơng có comment Thiết lập Cookie với Servlet Bạn theo bước sau để thiết lập Cookie với Servlet: http://vietjack.com/                                                                                                                              Trang  chia  sẻ  các  bài  học  online  miễn  phí  Page  1   http://vietjack.com/  servlets/index.jsp                                                                                                              Copyright  ©  vietjack.com     (1) Tạo đối tượng Cookie: Bạn gọi Cookie constructor với tên Cookie giá trị Cookie, hai String Cookie cookie = new Cookie("key","value"); Bạn nên nhớ rằng, tên giá trị không nên chứa khoảng trống trắng ký tự sau: [ ] ( ) = , " / ? @ : ; (2) Thiết lập tuổi tối đa: Bạn sử dụng setMaxAge để xác định thời gian (bằng giây) Cookie hiệu lực Ví dụ sau thiết lập Cookie 24 cookie.setMaxAge(60*60*24); (3) Gửi Cookie vào trường HTTP Response Header: Bạn sử dụngresponse.addCookie để thêm Cookie vào trường HTTP Response Header sau: response.addCookie(cookie); Ví dụ Chúng ta sửa đổi Ví dụ Form để thiết lập Cookie cho First Last name: // Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; // Extend HttpServlet class public class HelloForm extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Create cookies for first and last names Cookie firstName = new Cookie("first_name", request.getParameter("first_name")); Cookie lastName = new Cookie("last_name", request.getParameter("last_name")); // Set expiry date after 24 Hrs for both the cookies firstName.setMaxAge(60*60*24); lastName.setMaxAge(60*60*24); // Add both the cookies in the response header response.addCookie( firstName ); content type response.addCookie( lastName ); response.setContentType("text/html"); out = response.getWriter(); // Set response PrintWriter String title = "Setting Cookies Example"; String docType = "\n"; out.println(docType + "\n" + "" + title + "\n" + "\n" + "" + http://vietjack.com/                                                                                                                              Trang  chia  sẻ  các  bài  học  online  miễn  phí  Page  1   http://vietjack.com/  servlets/index.jsp                                                                                                              Copyright  ©  vietjack.com     title + "\n" + "
    \n" + "
  • First + request.getParameter("first_name") + "\n" + "
  • Last Name: " + request.getParameter("last_name") + "\n" + "
\n" + ""); } } Name: " Biên dịch HelloForm tạo entry thích hợp web.xml file cuối thử trang HTML sau để gọi Servlet: First Name: Last Name: Giữ nội dung HTML Hello.htm file đặt thư mục /webapps/ROOT directory Khi bạn truy cập http://localhost:8080/Hello.htm, output form trên: First Name: Last Name: Khi bạn nhập First Name Last Name sau nhấn nút Submit Nó hiển thị First Name Last Name hình thời điểm đó, thiết lập hai Cookie firstName lastName, mà truyền trở lại Server lần bạn nhấn nút Submit Phần tới giới thiệu cho bạn cách để truy cập Cookie trở lại ứng dụng web bạn Đọc Cookie với Servlet Để đọc Cookie, bạn cần tạo mảng đối tượng javax.servlet.http.Cookie việc gọi phương thức getCookies() HttpServletRequest Sau đó, tuần hoàn qua mảng, sử dụng phương thức getName() getValue() để truy cập Cookie giá trị liên kết Ví dụ Chúng ta đọc Cookie sau mà thiết lập ví dụ trước đó: // Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; // Extend HttpServlet class public class ReadCookies extends HttpServlet { public void doGet(HttpServletRequest http://vietjack.com/                                                                                                                              Trang  chia  sẻ  các  bài  học  online  miễn  phí  Page  1   http://vietjack.com/  servlets/index.jsp                                                                                                              Copyright  ©  vietjack.com     request, HttpServletResponse response) ServletException, IOException { throws Cookie cookie = null; Cookie[] cookies = null; // Get an array of Cookies associated with this domain cookies = request.getCookies(); // Set response content type response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Reading Cookies Example"; String docType = "\n"; out.println(docType + "\n" + "" + title + "\n" + "\n" ); if( cookies != null ){ out.println(" Found Cookies Name and Value"); for (int i = 0; i < cookies.length; i++){ cookie = cookies[i]; out.print("Name : " + cookie.getName( ) + ", "); out.print("Value: " + cookie.getValue( )+" "); out.println( "No cookies founds"); out.println(""); out.println(""); } } }else{ } } Biên dịch ReadCookie tạo entry thích hợp web.xml file Nếu bạn thiết lập first_name cookie “John” last_name cookie “Player”, chạyhttp://localhost:8080/ReadCookies hiển thị kết sau: Found Cookies Name and Value Name : first_name, Value: John Name : last_name, Value: Player Xóa Cookie với Servlet Xóa Cookie đơn giản Nếu bạn muốn xóa Cookie, đơn giản bạn cần theo bước sau: • Đọc cookie tồn lưu đối tượng Cookie • Thiết lập tuổi cookie sử dụng phương thức setMaxAge() để xóa cookie tồn • Thêm cookie trở lại bên trường Response header Ví dụ Ví dụ sau xóa cookie tồn với tên “first_name” bạn chạy Servlet ReadCookies lần trả giá trị null cho first_name http://vietjack.com/                                                                                                                              Trang  chia  sẻ  các  bài  học  online  miễn  phí  Page  1   http://vietjack.com/  servlets/index.jsp                                                                                                              Copyright  ©  vietjack.com     // Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; // Extend HttpServlet class public class DeleteCookies extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Cookie cookie = null; Cookie[] cookies = null; // Get an array of Cookies associated with this domain cookies = request.getCookies(); response.setContentType("text/html"); response.getWriter(); String docType = // Set response content type PrintWriter out = String title = "Delete Cookies Example"; "\n"; out.println(docType + + "" + title + "\n" + "\n" ); "\n" if( cookies != null ){ out.println(" Cookies Name and Value"); cookies.length; i++){ cookie = cookies[i]; for (int i = 0; i < if((cookie.getName( )).compareTo("first_name") == ){ cookie.setMaxAge(0); response.addCookie(cookie); out.print("Deleted cookie : " + ) + ""); } ) + ", } "); }else{ founds"); cookie.getName( out.print("Name : " + cookie.getName( out.print("Value: " + cookie.getValue( )+" "); } out.println(""); out.println( "No cookies out.println(""); } } Biên dịch DeleteCookies tạo entry thích hợp web.xml file Bây bạn chạyhttp://localhost:8080/DeleteCookies hiển thị kết quả: Cookies Name and Value Deleted cookie : first_name Name : first_name, Value: John Name : last_name, Value: Player http://vietjack.com/                                                                                                                              Trang  chia  sẻ  các  bài  học  online  miễn  phí  Page  1   http://vietjack.com/  servlets/index.jsp                                                                                                              Copyright  ©  vietjack.com     Bây chạy http://localhost:8080/ReadCookies hiển thị cookie sau: Found Cookies Name and Value Name : last_name, Value: Player Bạn xóa cookie bạn IE thao tác tay Bắt đầu Tools menu chọn Internet Options Để xóa tất cookie, nhấn Delete Cookies   http://vietjack.com/                                                                                                                              Trang  chia  sẻ  các  bài  học  online  miễn  phí  Page  1   ... HttpServletResponse response) ServletException, IOException { throws Cookie cookie = null; Cookie[ ] cookies = null; // Get an array of Cookies associated with this domain cookies = request.getCookies(); // Set... HttpServletResponse response) throws ServletException, IOException { Cookie cookie = null; Cookie[ ] cookies = null; // Get an array of Cookies associated with this domain cookies = request.getCookies(); response.setContentType("text/html");... last_name, Value: Player Xóa Cookie với Servlet Xóa Cookie đơn giản Nếu bạn muốn xóa Cookie, đơn giản bạn cần theo bước sau: • Đọc cookie tồn lưu đối tượng Cookie • Thiết lập tuổi cookie sử dụng phương

Ngày đăng: 02/12/2017, 22:29

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan