user93353 user93353 - 1 month ago 17
Java Question

Java Servlets: Different kinds of attributes

Was going through some Java Servlets code.

I found attributes set and retrieved in 3 different ways.

req.getSession().setAttribute("var1","value1");
req.setAttribute("var2", "value2");
getServletContext().setAttribute("var3", "value3");


req
is a variable of type
HttpServletRequest

I am a little confused as to what is the difference between the three?

Answer

req.getSession().setAttribute("var1","value1"); - Is a Session Attribute.

req.setAttribute("var2", "value2"); - Is a Request Attribute.

getServletContext().setAttribute("var3", "value3"); - Is a Servlet Context Level (an Application) Attribute.