AustinT AustinT - 3 months ago 25
Java Question

Differences between attributes in Request, Session and ServletContext

I am having trouble understanding the differences between these 3 ways of setting attributes:

// String as attribute of request
req.setAttribute("name", "Sluggo");

// Integer as attribute of session
req.getSession().setAttribute("age", 10);

// Date as attribute of context
getServletContext().setAttribute("today", new Date());

  1. What are the differences?

  2. When should you use each?


all three have different scope,

request's attribute lives for that request response cycle,

session's attribute for that session,

servletContext is across the servlet context and it lives until context gets destroyed