To use the instance created by the Servlet class in the JSP file, use the area called Scope where the instance can be saved. There are three types of scopes to use: "request scope", "session scope", and "application scope", and the expiration date when the instance is saved differs depending on each scope.
Below is the basic syntax for each scope.
Use when you want to share data between requests.
python
//Save to request scope
request.setAttribute("Attribute name",instance);
//Get from request scope
Instance type Variable name= (Instance type) request.getAttribute("Attribute name");
Used when you want to share data between HTTP sessions
python
//Get Session scope(Secure storage area)
HttpSession session = request.getSession(true);
//Save to session scope
session.setAttribute("Attribute name",instance);
//Obtained from session scope
Instance type Variable name= (Instance type) session.getAttribute("Attribute name");
//Erase from session scope
session. removeAttribute ("Attribute name");
//Discard session scope(End)
session.invalidate();
Used when you want to share data between web applications.
python
//Get application scope(Secure storage area)
ServletContext sc = getServletContext();
//Save to application scope
sc.setAttribute("Attribute name",instance);
//Get from application scope
Instance type Variable name= (Instance type) sc.getAttribute("Attribute name");
//Erase from application scope
session.removeAttribute ("Attribute name");
The table below summarizes it.
Recommended Posts