Common Methods
1. setAttribute(String name, Object value)
This associates the specified value to the specified name in a particular session. This can be used to store data that needs to be managed across multiple requests.
HttpSession session = request.getSession();
session.setAttribute("username", "GFG");
2. getAttribute(String name)
Returns the value which is associated with the specified name in the particular session. This is used to retrieve previously stored session attributes.
HttpSession session = request.getSession();
String username = (String) session.getAttribute("username");
3. removeAttribute(String name)
It removes the attribute with the specified name from the session.
HttpSession session = request.getSession();
session.removeAttribute("username");
4. invalidate()
Once the services are completed, it is necessary to destroy the session object. The syntax follows.
HttpSession session = request.getSession();
session.invalidate();
Example
Java
import javax.servlet.http.*; @WebServlet ( "/api" ) public class GFG extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) { // Retrieve the HttpSession object HttpSession session = request.getSession(); // Use HttpSession methods session.setAttribute( "username" , "GFG" ); String value = (String) session.getAttribute( "username" ); } } |
In the above example, the getSession() method is called on the HttpServletRequest object to retrieve the HttpSession. Once you have the HttpSession object, you can use its methods to set and retrieve session attributes.
Session Management in Java
Session is used to save user information momentarily on the server. It starts from the instance the user logs into the application and remains till the user logs out of the application or shuts down the machine. In both cases, the session values are deleted automatically. Hence, it functions as a temporary storage that can be accessed till the user is active in the application and can be accessed when the user requests a URI. This session is stored in binary values, hence maintaining the security aspect, and can be decoded only at the server end.
Contact Us