What are the scopes in jsp?

Most of the time in jsp you need scopes to get and set attributes. In addition to the servlet request, session, application(context) jsp has another “page” scope that you can get from the pageContext object.

Scope---In Servlet vs In JSP
Application---getServletContext().setAttribute()---application.setAttribute()
Request---request.setAttribute()---request.setAttribute()
Session---session().setAttribute()---session.setAttribute()
Page---(not in servlet)---pageContext.setAttribute()


The request scope exists until the client get the response. Session scope exists for a client till the session ends. Context scope is available always for all the servlets and jsps. Page scope is needed at the time of developing custom tags.
You can use a page scope to get attributes from any other scope. To get and set the attributes for any scope by pageContext we can use APPLICATION_SCOPE, PAGE_SCOPE, REQUEST_SCOPE, SESSION_SCOPE. Methods to get any scope from pageContext are getRequest(), getServletContext(), getServletConfig(), getSession().


Setting/Getting page scope:
pageContext.setAttribute(“name”,”bhabani”);
pageContext.getAttribute(“name”);

Using page scope to set/get session scope attributes:
pageContext.setAttribute(“name”,”bhabani”,pageContext.SESSION_SCOPE);
pageContext.getAttribute(“name”, pageContext.SESSION_SCOPE);

Using page scope to get/set application scope attributes:
pageContext.setAttribute(“name”,”bhabani”,pageContext.APPLICATION_SCOPE);
pageContext.getAttribute(“name”,pageContext.APPLICATION_SCOPE);

Using pageContext to get unknown scope attribute:
pageContext.findAttribute(“name”);
First it looks the pageContext after that it looks for other scopes(request then session then application) for “name”. The first attribute it finds with that name it stops searching.

No comments:

Post a Comment