The article directories

    • 1.Cookie
      • 1.1 Creating a Cookie
      • 1.2 Setting the Cookie Expiration Time
      • 1.3 Setting the Cookie Domain
      • 1.4 Setting the Cookie Path
      • 1.5 Reading Cookies in servlets
      • 1.6 delete the Cookie
    • 2. HttpSession
      • 2.1 Obtaining a Session
      • 2.2 Session Attributes

1.Cookie

In short, a cookie is a small piece of data stored on a client that the server uses when communicating with the client.

They are used to identify the client when sending subsequent requests. They can also be used to pass some data from one servlet to another.

See this article for more details.

1.1 Creating a Cookie

The cookie class defines the Javax.servlet. HTTP package encapsulation.

To send it to the client, we need to create one and add it to the response:

Cookie uiColorCookie = new Cookie("color"."red");
response.addCookie(uiColorCookie);
Copy the code

1.2 Setting the Cookie Expiration Time

We can set the maximum age (using the method maxAge (int)), which defines how many seconds a given Cookie will be valid:

uiColorCookie.setMaxAge(60*60);
Copy the code

We set the maximum age to one hour. After this time, clients (browsers) cannot use cookies when sending requests and should remove them from the browser cache.

1.3 Setting the Cookie Domain

Another useful method in the Cookie API is setDomain (String).

This allows us to specify the domain to which the client should deliver it. It also depends on whether we specify the domain name explicitly.

Let’s set the field for cookies:

uiColorCookie.setDomain("example.com");
Copy the code

This Cookie is passed to each request made by Example.com and its subdomains.

If we do not explicitly specify a domain, it is set to the domain to create the cookie.

For example, if we create a cookie from example.com and leave the domain name empty, it will be sent to www.example.com (without subdomains).

In addition to the domain name, we can also specify the path. So let’s see.

1.4 Setting the Cookie Path

This path specifies the location to which the cookie is passed.

If we specify a path explicitly, the Cookie will be passed to the given URL and all its subdirectories:

uiColorCookie.setPath("/welcomeUser");
Copy the code

Implicitly, it will be set to the URL that creates the cookie and all of its subdirectories.

For now, let’s focus on how to retrieve their values in servlets.

1.5 Reading Cookies in servlets

Cookies are added to the request by the client. The client checks its parameters and decides if it can be passed to the current URL.

We can retrieve all cookies by calling getCookies () on the request passed to the Servlet (HttpServletRequest).

We can iterate over this array and search for the desired arrays, for example, by comparing their names:

public Optional<String> readCookie(String key) {
    return Arrays.stream(request.getCookies())
      .filter(c -> key.equals(c.getName()))
      .map(Cookie::getValue)
      .findAny();
}
Copy the code

1.6 delete the Cookie

To remove the Cookie from the browser, we must add a Cookie of the same name to the response, but its maxAge value should be set to 0:

Cookie userNameCookieRemove = new Cookie("userName"."");
userNameCookieRemove.setMaxAge(0);
response.addCookie(userNameCookieRemove);
Copy the code

An example use case for deleting cookies is a user logout operation – we may need to delete some data stored for an active user session.

Now we know how to handle cookies in servlets.

Next, we’ll take a look at our Servlet from another important target that we visit very frequently – a session object.

2. HttpSession

In HttpSession, another option for storing user-related data across different storage requests. A session is a server-side store that holds context data.

Data is not shared between different session objects (clients can access data only from their sessions). It also contains key-value pairs, but in contrast to cookies, sessions can contain objects as values. The storage implementation mechanism depends on the server.

The session matches the client through cookies or request parameters. More information can be found here.

2.1 Obtaining a Session

We can get HttpSession directly from the request:

HttpSession session = request.getSession();
Copy the code

If the above code does not exist, it creates a new session. We can accomplish the same thing by calling the following command:

request.getSession(true)
Copy the code

If we just want to get an existing session without creating a new one, we need to use:

request.getSession(false)
Copy the code

If we are accessing a JSP page for the first time, a new session is created by default. We can disable this behavior by setting the session property to false:

<%@ page contentType="text/html; charset=UTF-8" session="false"% >Copy the code

In most cases, Web servers use cookies for session management. After the session object is created, the server creates a cookie with a JSESSIONID key and a value that identifies the session.

2.2 Session Attributes

Session objects provide a number of methods to access (create, read, modify, delete) properties created for a given user session:

  • SetAttribute (String, Object), which creates or replaces session attributes with keys and new values
  • GetAttribute (String) reads the value of the attribute with the given name (key)
  • RemoveAttribute (String) Removes the attribute with the given name

We can also easily check existing session attributes by calling getAttributeNames ().

As mentioned earlier, we can retrieve the session object from the request. When we already have it, we can quickly implement the above method.

We can create a property:

HttpSession session = request.getSession();
session.setAttribute("attributeKey"."Sample Value");
Copy the code

The attribute value can be obtained by its key (name) :

session.getAttribute("attributeKey");
Copy the code

We can delete attributes that are no longer needed:

session.removeAttribute("attributeKey");
Copy the code

A well-known use case for user sessions is that when a user logs out of our site, the entire stored data becomes invalid. Session objects provide a solution for this:

session.invalidate();
Copy the code

This method removes the entire session from the Web server, so we can no longer access properties from it.

The HttpSession object has more methods, but the ones we mentioned are the most common.

Translation:

  • www.baeldung.com/java-servle…

🍎QQ group [837324215] 🍎 pay attention to my public number [Java Factory interview officer], learn together 🍎🍎🍎