AustinT AustinT - 1 year ago 97
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?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download