Class HttpSession

java.lang.Object
com.codename1.backend.HttpSession

public final class HttpSession extends Object

State kept for one client across requests, found again through a cookie.

@PostMapping("/login")
  public void login(HttpServer.Request request, @RequestBody Map body) {
      ...
      HttpSession session = request.getSession(true);
      session.changeSessionId();          // never keep a pre-login id
      session.setAttribute("user", userId);
  }

A session is created only when something asks for one with getSession(true), so a server that never does sets no cookie and keeps nothing. The cookie is HttpOnly, SameSite=Lax and, on a TLS server, Secure; its name, lifetime and store are configured under cn1.session.*. See Sessions.

Attributes live in the SessionStore. The in-memory store keeps any object; the database store keeps what Json can write -- strings, numbers, booleans, and maps and lists of those -- because it has to read them back in another process.

A @SessionScope bean is never written to a store: the server that built it keeps it in memory for as long as the session lives, and runs its destroy methods when the session is invalidated, expires or the server stops. Another instance behind a load balancer builds its own.

  • Method Details

    • getId

      public String getId()
      The id the cookie carries. Secret: never log it.
    • isNew

      public boolean isNew()
      Whether this session was created by the current request.
    • getCreationTime

      public long getCreationTime()
    • getLastAccessedTime

      public long getLastAccessedTime()
    • getMaxInactiveInterval

      public int getMaxInactiveInterval()
      Seconds of inactivity after which the session is discarded.
    • setMaxInactiveInterval

      public void setMaxInactiveInterval(int seconds)
    • getAttribute

      public Object getAttribute(String name)
    • setAttribute

      public void setAttribute(String name, Object value)
    • removeAttribute

      public void removeAttribute(String name)
    • getAttributeNames

      public List getAttributeNames()
      The attribute names, as a copy.
    • invalidate

      public void invalidate()
      Ends the session: its attributes are dropped and the client's cookie cleared.
    • isValid

      public boolean isValid()
    • changeSessionId

      public String changeSessionId()

      Gives the session a new id, keeping its attributes, and sends the client the new cookie. Call it when a user signs in: an id a client held before authenticating is one an attacker may have planted.

      Returns

      the new id

    • beanLock

      public Object beanLock()
      What generated code locks while it builds one of this session's beans: an object every loaded copy of the session shares.
    • scopedBeans

      public Object[] scopedBeans(int count)
      The @SessionScope beans of this session, by the slot the build gave each. Called by generated code.