CÔNG NGHỆ THÔNG TIN >> BÀI VIẾT CHỌN LỌC

[Java Web] State management sử dụng Session và Cookie trong JSP Servlet

Đăng lúc: 08:12 PM - 30/01/2024 bởi Charles Chung - 817

HTTP là một giao thức trao đổi thông tin trên môi trường internet giữa các máy client và server và nó là giao thức phi trạng thái, để giải quyết vấn đề client và server có thể lưu lại trạng thái trong quá trình giao tiếp thì Session và Cookie và một giải pháp. Trong bài này chúng ta sẽ tìm hiểu về Session và Cookie trong JSP Servlet

Cookie là gì?

Cookie là đoạn văn bản hoặc thông tin được tạo ra bởi server và gửi về client để lưu lại. Chúng chủ yếu được sử dụng để nhận dạng người dùng trên Web Server. Hơn nữa, tất cả các cookie lưu ở client (trong cùng domain) sẽ được gửi đến server trong các request tiếp theo để máy chủ có thể xác định người dùng hoặc có thể sử dụng nó cho các mục đích khác như theo dõi, v.v. Client có thể xóa cookie hoặc chúng hết hạn khi đạt đến MaxAge.

Các loại Cookie

Về cơ bản có hai loại cookie:

  1. Persistent Cookie: Những cookie này còn được gọi là cookie vĩnh viễn. Chúng vẫn còn trên ổ cứng và tồn tại cho đến khi người dùng xóa chúng hoặc chúng hết hạn.
  2. Session Cookie: Những cookie này còn được gọi là cookie tạm thời. Chúng sẽ tự xóa ngay khi session kết thúc hoặc trình duyệt đóng.

Ứng dụng của Cookie

  • Cookie có thể được sử dụng để ghi nhớ tên người dùng và mật khẩu của bất kỳ trang web nào.
  • Cookie có thể được sử dụng để quản lý Session. Máy chủ có thể lưu trữ SESSION ID ở phía client. Khi phương thức getSession() được gọi thì SESSION ID này có thể được client gửi đến server để xác định nó.
  • Việc quản lý session bằng cookie không thành công đối với người dùng khiến cookie của họ bị chặn vì không thể lưu thông tin nào về phía client.
  • Cookie có thể được sử dụng để ghi nhớ sở thích của người dùng.
  • Chúng ta có thể sử dụng phương thức isRequestSessionIdFromCookie để xem cookie có đang được sử dụng hay không. Nếu phương thức này trả về true thì cookie đang được sử dụng nếu không thì không.

Làm việc với Cookie trong JSP

  • Tạo cookie 
Cookie cookie = new Cookie("key","value");

Hãy nhớ rằng tên và giá trị không được chứa khoảng trắng hoặc bất kỳ ký tự nào sau đây: 

[ ] ( ) = , " / ? @ : ;
  • Thiết lập thời gian tồn tại cookie: sử dụng phương thức setMaxAge(seconds), trong ví dụ dưới là 24 giờ
cookie.setMaxAge(60*60*24);
  • Gửi cookie về client thông qua Response HTTP Headers
response.addCookie(cookie);
  • Đọc cookie: sử dụng phương thức request.getCookies() trả về một mảng đối tượng Cookie, từ đó chúng ta có thể đọc ra thông tin từng cookie.

Một số phương thức của đối tượng Cookie

S.No. Method & Description
1

public void setDomain(String pattern)

This method sets the domain to which the cookie applies; for example, tutorialspoint.com.

2

public String getDomain()

This method gets the domain to which the cookie applies; for example, tutorialspoint.com.

3

public void setMaxAge(int expiry)

This method sets how much time (in seconds) should elapse before the cookie expires. If you don't set this, the cookie will last only for the current session.

4

public int getMaxAge()

This method returns the maximum age of the cookie, specified in seconds, By default, -1 indicating the cookie will persist until the browser shutdown.

5

public String getName()

This method returns the name of the cookie. The name cannot be changed after the creation.

6

public void setValue(String newValue)

This method sets the value associated with the cookie.

7

public String getValue()

This method gets the value associated with the cookie.

8

public void setPath(String uri)

This method sets the path to which this cookie applies. If you don't specify a path, the cookie is returned for all URLs in the same directory as the current page as well as all subdirectories.

9

public String getPath()

This method gets the path to which this cookie applies.

10

public void setSecure(boolean flag)

This method sets the boolean value indicating whether the cookie should only be sent over encrypted (i.e, SSL) connections.

11

public void setComment(String purpose)

This method specifies a comment that describes a cookie's purpose. The comment is useful if the browser presents the cookie to the user.

12

public String getComment()

This method returns the comment describing the purpose of this cookie, or null if the cookie has no comment.

Session là gì?

Session là một khái niệm rất quen thuộc trong Lập trình Web, một session đại diện cho một phiên làm việc giưa Client và Server, nó bắt đầu khi client gửi request đến server, nó tồn tại xuyên suốt từ trang này đến trang khác trong ứng dụng web và chỉ kết thúc khi hết thời gian timeout hoặc khi bạn đóng ứng dụng.

Hoạt động của Session

Khi một phiên làm việc giữa Client và Server được khởi tạo, Server sẽ sinh ra một SESSION ID và gửi về Client và lưu bằng một trong các cách như: cookie, url rewrite, hidden field. Đồng thời SESSION ID đó kèm dữ liệu cũng được lưu trên Server, các request tiếp theo từ Client gửi lên sẽ kèm theo SESSION ID và dựa vào đó Server xác định được dữ liệu liên quan đến phiên việc đó.

Làm việc với Session trong JSP

  • Trong trang JSP luôn cung cấp đối tượng mặc định là session cho người dùng nên người lập trình có thể ngay lập tức bắt đầu lưu trữ và truy xuất dữ liệu từ đối tượng mà không cần khởi tạo, còn trong Servlet người dùng chỉ cần gọi lệnh request.getSession() để sử dụng session.

Một số phương thức của Session

S.No. Method & Description
1

public Object getAttribute(String name)

This method returns the object bound with the specified name in this session, or null if no object is bound under the name.

2

public Enumeration getAttributeNames()

This method returns an Enumeration of String objects containing the names of all the objects bound to this session.

3

public long getCreationTime()

This method returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT.

4

public String getId()

This method returns a string containing the unique identifier assigned to this session.

5

public long getLastAccessedTime()

This method returns the last time the client sent a request associated with the this session, as the number of milliseconds since midnight January 1, 1970 GMT.

6

public int getMaxInactiveInterval()

This method returns the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses.

7

public void invalidate()

This method invalidates this session and unbinds any objects bound to it.

8

public boolean isNew()

This method returns true if the client does not yet know about the session or if the client chooses not to join the session.

9

public void removeAttribute(String name)

This method removes the object bound with the specified name from this session.

10

public void setAttribute(String name, Object value)

This method binds an object to this session, using the name specified.

11

public void setMaxInactiveInterval(int interval)

This method specifies the time, in seconds, between client requests before the servlet container will invalidate this session.

Ví dụ:

Yêu cầu: Project sẽ gồm trang index.jsp hiển thị trang chủ và menu đăng nhập (nếu người dùng chưa đăng nhập), hiển thị lời chào và menu thoát (nếu người dùng đã đăng nhập), trang login.jsp cung cấp form login cho người dùng, nếu cookie được lưu thì sẽ đọc thông tin cookie lên form, nếu chưa thì để form trắng. Khi kích vào login sẽ gọi tới LoginServer và khởi tạo Session để lưu username, nếu remember password được chọn thì lưu username và password vào cookie, tại trang chủ nếu menu thoát được kích thì chuyển tới LogoutServlet và xóa Session.

Bước 1: Mở Eclipse tạo một Dynamic Web Project đặt tên "JSPServletSession03"

Bước 2: Tạo các trang JSP và Servlet theo cấu trúc dưới

Bước 3: Bổ sung code cho các trang JSP và Servlet theo gợi ý sau

Trang index.jsp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<%@ page language="java" contentType="text/html; charset=UTF-8"	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Tìm hiểu về Session và Cookie trong JSP and Servlet</title>
<style>
#nav {
	width: 1200px;
	margin: auto;
	height: 30px;
}

#content {
	width: 1200px;
	margin: auto;
	height: 500px;
	background-color: gray;
	color: white;
	padding: 20px;
}
</style>
</head>
<body>
	<div id="nav">
		<a href="index.jsp">Trang chủ </a>|
		<%
		if (session.getAttribute("username") != null) {
		%>
		Xin chào:${sessionScope.username} <a href="LogoutServlet"> Thoát</a>
		<%
		} else {
		%>
		<a href="login.jsp"> Đăng nhập</a>
		<%
		}
		%>
	</div>
	<div id="content">
		<h2>Tìm hiểu về Session và Cookie trong JSP and Servlet</h2>
	</div>
</body>
</html>

Trang login.jsp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Đăng nhập</title>
</head>
<body>
<h1>Đăng nhập</h1>
<span style="color:red">${msg}</span>
<form action="LoginServlet" method="post">
<table>
	<tr>
		<td>Tên đăng nhập</td>
		<td><input type="text" name="username" value="${cookie.username.value}"/></td>
	</tr>
	<tr>
		<td>Mật khẩu</td>
		<td><input type="password" name="password"  value="${cookie.password.value}"/></td>
	</tr>
	<tr>
		<td colspan="2"><input type="checkbox" name="remember" checked="checked"/> Nhớ mật khẩu</td>
	</tr>
	<tr>
		<td colspan="2"><button>Đăng nhập</button></td>
	</tr>
</table>
</form>

</body>
</html>

Lớp LoginServlet.java phương thức doGet

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username=request.getParameter("username");
		String password=request.getParameter("password");
		String remember=request.getParameter("remember");
		if(username.equals("hanam88") & password.equals("123456")) {
			HttpSession session=request.getSession(true);
			session.setAttribute("username", username);
			session.setMaxInactiveInterval(3600);
			if(remember!=null)
			{
				Cookie usercookie=new Cookie("username", username);
				Cookie passcookie=new Cookie("password", password);
				usercookie.setMaxAge(120);
				passcookie.setMaxAge(120);
				response.addCookie(usercookie);
				response.addCookie(passcookie);				
			}
            response.sendRedirect("index.jsp");
		}else
		{
			request.setAttribute("msg", "Đăng nhập sai");
			request.getRequestDispatcher("login.jsp").forward(request, response);
		}
	}

Lớp LogoutServlet.java phương thức doGet

1
2
3
4
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getSession().invalidate();
		response.sendRedirect("login.jsp");
	}

Bước 4: Run Application và xem kết quả

  • Màn hình index.jsp khi chưa đăng nhập

  • Màn hình index.jsp khi đăng nhập

  • Màn hình login.jsp khi chưa lưu cookie

  • Màn hình login.jsp khi đã lưu cookie

Link download source code tham khảo

Video demo

thay lời cảm ơn!

QUẢNG CÁO - TIẾP THỊ