Among different techniques for session management in servlet, we will learn about one of them i.e. HTTPSession to manage the session. In the previous technique, we have learned session management using URL Rewriting Here we will learn the Fourth and last techniques HttpSession to manage the session. Before discussing this technique in detail let’s first understand about HttpSession.
- What is HttpSession?
- How to get a HttpSession Object?
- How HttpSession Work?
- Methods of HttpSession Interface
- HttpSession Example
The HttpSession interface is implemented by the server. The servlet container uses this interface to create a session between the Http client and Http server. It allows the servlet to read and write the state information that is involved with an HttpSession.
There are 2 different methods to obtain the HttpSession Object
1. public HttpSession getSession(): This method returns the current session associated with this request or if the request doesn’t have any session it creates a new session,
2. public HttpSession getSession(boolean create): This method returns the HttpSession object. It returns the HttpSession object if a request has a session otherwise it returns null.
On the left side, there are two clients and in the center, there is a container (webserver). The first client sends the request to the web server, the web server creates the SessionId for the first client and this Session Id send back to the first client. If the first client makes a further request for the second request, the session id will be a part of this request so that the container can identify the particular user using the session id.
If the second client sends the request to a web server, the web server creates the session for the second client and this Session Id sends it back to the second client. if the second client makes a further request for the second request the session id will be part of this request so the container can identify the particular user using the session id.
- Session Tracking in Servlet and its Techniques
- Servlet interface and its methods explained with example
- What is Servlet in Java
1. public long getCreationTime(): It returns the time(in milliseconds since midnight, January 1, 1970, GMT) when the session was created.
2. public String getId(): It returns the session Id.
3. public void invalidate(): Invalidates this session and removes it from the context.
4. public boolean isNew(): It Returns true if the server created the session and is not yet accessed by the client.
5. public void setAttribute(String str, object obj): Associated the value passed in obj with the attribute name passed in str.
6. public long getLastAccessedTime(): It returns the time(in milliseconds since midnight, January 1, 1970, GMT)when the client last made a request for this session.