Are session and sessionScope the same in JSP EL?
Asked Answered
N

5

21
public class LoginAction extends ActionSupport {
    private String username;
    private String password;

    @Override
    public String execute() throws Exception {
        ActionContext ctx = ActionContext.getContext();
        Integer counter = (Integer)ctx.getApplication().get("counter");
        // put counter into application 
        ctx.getApplication().put("counter", counter);
        // put username into session
        ctx.getSession().put("user", username);
        if (getUsername().equals("crazyit.org")
                && getPassword().equals("leegang")) {
            ctx.put("tip", "Login Success! ");
            return SUCCESS;
        }
        else {
            ctx.put("tip", "Login Falied!");
            return ERROR;
        }        
    }
}

I put "counter" in application "user" in session and "tip" in ActionContext. In JSP I can use ${session.user} and ${sessionScope.user} to reference the "user" property. ${request.tip} and ${requestScope.tip} to reference tip.

My questions:

  1. Are session, request, application the same as sessionScope, requestScope, applicationScope in EL?
  2. What's the relationship between ActionContext and request(requestScope)?

P.S.:

I test ${request == requestScope} which is true, this means they are the same?

Normannormand answered 11/7, 2013 at 10:7 Comment(0)
M
28

With expression language (EL), the scope items are value maps of attributes in the objects that they refer to. For instance, the requestScope is a map representation of values in the request object. This is explained in pretty clear detail on this page: Java Servlet and JSP. If you read through the EL sections, you'll notice a point about request vs request scope here: The requestScope is NOT request object.

I would recommend reading through this page to get a better understanding of servlet/jsp in general.

As far as how the ActionContext relates to these items, it is really a wrapper used by struts to encapsulate the servlet. You can read more specifics about it here: Accessing application, session, request objects.

There have been some references to implicit values given here, but I feel like just saying it's implicit doesn't really explain much. When you are using EL to access servlet variables, you can explicitly declare which scope you want to reference, such as:

 ${requestScope.myVariable}

You can also reference it implicitly by omitting the scope:

 ${myVariable}

Now, the problem that can arise here is that variables with the same name can cause collision. EL will check implicit values in a specific order: pageScope, requestScope, sessionScope, and applicationScope, param, paramValues, header, headervalues, initParam, cookie, pageContext. What this means is that if you have a variable in the request scope with the same name as a variable in session or application scope for instance, the request scoped value will be referenced.

Membership answered 11/7, 2013 at 13:13 Comment(3)
Thanks for the referenced materials, I would figure out myself.Normannormand
Where can I find the documentation about the specific order you mentioned when scope is omitted in EL? Thanks!Tinge
I can't remember where specifically I found it, but there is some information here: docs.oracle.com/cd/E19159-01/819-3669/bnaij/index.html which states: "For example, when evaluating the expression ${product}, the resolver will look for product in the page, request, session, and application scopes and will return its value. If product is not found, null is returned." Doing a Google search for "IMPLICIT objects available to JSP EL order of access" also provides tons of starting points for research.Membership
L
24

By default page, request, session and application scope objects are available to JSP pages. So you can access then using EL syntax.

And following table shows IMPLICIT objects available to EL.

       Implicit object            Description
1.     pageScope        Scoped variables from page scope
2.     requestScope     Scoped variables from request scope
3.     sessionScope     Scoped variables from session scope
4.     applicationScope Scoped variables from application scope
5.     param            Request parameters as strings
6.     paramValues      Request parameters as collections of strings
7.     header           HTTP request headers as strings
8.     headerValues     HTTP request headers as collections of strings
9.     initParam        Context-initialization parameters
10.    cookie           Cookie values
11.    pageContext      The JSP PageContext object for the current page

So session and sessionScope are same but differs in context they are used.More specifically session is object and sessionScope is map (key, value) of Attribute and its value.

  • If you say ${session.sessionAttr} it refers to session object available to JSP page.
  • If you say ${sessionScope.sessionAttr} it refers to IMPLICIT session object available to EL.
  • Or if you just say ${attrName} it will search attrName in all scope from page to application scope.
Luftwaffe answered 11/7, 2013 at 11:51 Comment(5)
Is the order here (from 1 to 10) the specific order EL will look up when no scope is specified?Tinge
Thanks! Is there any reference (documentation) about this?Tinge
Reference for you my dear friend @RoyLingLuftwaffe
Thanks! really helpful.Hyder
EL duplicates those objects for its self-style usage. But it may cause confusion to jsp beginners.Hyder
S
4
  1. session, request, application are the actually HttpSession,HttpServletRequest and ServletContext objects while sessionScope, requestScope and applicationScope provide access to all the session, request and application scoped attributes.

You can say that applicationScope > sessionScope > requestScope.

  • applicationScope attributes will be accessible to all the sessions, all the requests across the web applications. These attributes stay alive as long as application is alive
  • sessionScope attributes will be accessible to all the requests across the current HttpSession. These attributes stay alive as long as session is alive
  • requestScope attributes will be accessible from the current request only. Once the response is completed, they are gone.
Spheroid answered 11/7, 2013 at 10:12 Comment(2)
does that mean that "requestScope" also includes all attributes from "sessionScope" and "applicationScope" (whereas "request" does not)?Woodchopper
No, all the scopes have different attributes. What you can say is that The narrowest scope is reqeustScope, then sessionScope and then application scope.Spheroid
R
2

The ActionContext is a Struts2 thing, and it's created in every request that is handled by the framework. When it's created the framework populates it along with the servlet stuff with it's own implementations of request, session, and applicaton. And where you using it in the application these objects are referenced. To access the servlet stuff use the ServletActionContext that helps to retrieve the appropriate resources. Struts2 also wraps the ServletRequest to provide access to the action properties and valueStack from the EL expressions. sessionScope, requestScope, and applicationScope used with EL expressions to evaluate to the servlet stuff attributes. That are the differences.

Renascence answered 11/7, 2013 at 17:44 Comment(0)
D
1

Have a look over below given code I tried.

<body>
<%
FirstServlet first=new FirstServlet();  // it has a fileName property and getter setter for it
%>
<%
session.setMaxInactiveInterval(10); //jsp's implicit session object
request.setAttribute("session", first); //jsp's implicit request object
session.setAttribute("hello", "this worked!");
pageContext.getSession().setAttribute("hello", "now this also worked!");%> // same as above

${pageContext.session.maxInactiveInterval } // client's session object
${sessionScope.maxInactiveInterval}
${session.fileName } // FirstServlet Object and gives the fileName I gave.
${sessionScope.hello } // OP: "now this also worked!
${session==sessionScope } // gives false. If using struts2 than true
${request==requestScope } // gives false. If using struts2 than true
</body>

in EL as stated by Prasad and Captain when you use ${sessionScope} it only maps session-scoped variable names to their values.

if you want to get client's session object than you should use pageContext.session

but when you use ${session}, el searches for attribute maped with session name in order: page->request->session->application scopes starting from left to right.

${request == requestScope} gives false because requestScope is client's request object when request will cause EL to search for object maped with request name in various scopes . But in your case it is true because of struts2

Daughtry answered 11/7, 2013 at 13:30 Comment(4)
jsp's implicit session object and client's session object(${pageContext.session}) are not the same? can you explain a bit more?Normannormand
And why in struts2 request is equal to requestScope? Can you referenced some materials to me?Normannormand
JSP's session and ${pageContext.session} are same objects, but ${session} and ${sessionScope} are not same. jsp EL does not has session as a implicit object instead it has sessionScope as a implicit object but it only maps session-scoped variable names to their values which we set using session.setAttribute() so when you want to refer to client's than pageContext.session is preferable. This is a link to the official EL documentation.Daughtry
${session.getClass().getSimpleName() } gave me SessionMap as output and after lot of search and by refering EL example link and Struts 2 SessionMap i assume that Struts 2 and JSP EL refers to same object when we write ${session} and ${sessionScope} while using struts 2.Daughtry

© 2022 - 2024 — McMap. All rights reserved.